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

时间:2017-07-05 06:19:30

标签: c# wpf xaml

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

1 个答案:

答案 0 :(得分:4)

是的,您可以使用Assembly.LoadFile

动态加载程序集
Assembly.LoadFile("c:\\somefolder\"PathToCode.dll");

然后,您将需要使用Reflection来获取要调用的函数的methodinfo,或者使用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);
相关问题