如何在不添加引用的情况下从另一个项目调用 c# 函数?

Vai*_*ava 0 c# wpf xaml

有一个 C#.net 库项目,其 DLL 名称为customer.dll. 它有一个类名customer和一个函数名show()。我想从另一个项目调用这个函数,但不想添加对调用者项目的引用。这能做到吗?是否有任何 C#.net 类可以实现这一点?

Ale*_*ins 7

是的,您可以使用动态加载程序集 Assembly.LoadFile

Assembly.LoadFile("c:\\somefolder\"PathToCode.dll");
Run Code Online (Sandbox Code Playgroud)

然后,您将需要使用反射来获取要调用的函数的方法信息,或者使用 Dynamic 关键字来调用它。

var externalDll = Assembly.LoadFile("c:\\somefolder\\Customer.dll");
var externalTypeByName = externalDll.GetType("CustomerClassNamespace.Customer");

// If you don't know the full type name, use linq
var externalType = externalDll.ExportedTypes.FirstOrDefault(x => x.Name == "Customer");

//if the method is not static create an instance.
//using dynamic 
dynamic dynamicInstance = Activator.CreateInstance(externalType);
var dynamicResult = dynamicInstance.show();

// or using reflection
var reflectionInstance = Activator.CreateInstance(externalType);
var methodInfo = theType.GetMethod("show");
var result = methodInfo.Invoke(reflectionInstance, null);

// Again you could also use LINQ to get the method
var methodLINQ = externalType.GetMethods().FirstOrDefault(x => x.Name == "show");
var resultLINQ = methodLINQ.Invoke(reflectionInstance, null);
Run Code Online (Sandbox Code Playgroud)