fav*_*r85 5 .net c# reflection
我有一个.dll和一个控制台应用程序使用所述.dll但不直接引用,它通过反射加载它.控制台应用程序在.dll中调用类的方法.
方法签名是IEnumerable<Customer> GetAll();
在.dll我这样做了:
class CustomerRepository : ICustomerRepository
{
public IEnumerable<Customer> GetAll()
{
using (var db = new DB02Context())
{
List<Customer> list = new List<Customer>();
// some queries to fill the list
return list;
}
}
}
Run Code Online (Sandbox Code Playgroud)
在控制台应用程序中我做到了这一点:
Assembly assembly = Assembly.LoadFrom(pathToMyDLL);
Type t = assembly.GetType("MyDLL.Models.CustomerRepository");
var methodInfo = t.GetMethod("GetAll");
if(methodInfo == null)
throw new Exception("The method doesn't exists");
var customerRepository = Activator.CreateInstance(t);
// Invoke the GetAll() method
var customerList = methodInfo.Invoke(customerRepository, null);
Run Code Online (Sandbox Code Playgroud)
现在问题是,因为GetAll返回IEnumerable<Customer>并且我的控制台应用程序不"知道"任何关于MyDLL.dll的内容(我不直接引用它,所以它不知道Customer类型).
如何访问Customer列表以访问Customer'a属性而无需明确地引用.dll?
你有三个选择
Client接口Client实现移动或移动到反射DLL和控制台应用程序都可以引用的第3个dll.dynamic关键字作为对象的类型(dynamic customerList = methodInfo.Invoke(...),这是它发明的确切情况.IEnumerable并使用反射调用来调用返回Client的object对象上的方法IEnumerable.