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