我有一个.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;
}
}
}
在控制台应用程序中,我这样做:
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);
现在的问题是,由于GetAll返回IEnumerable<Customer>
并且我的控制台应用程序不“了解”有关MyDLL.dll的任何信息(我没有直接引用它,因此它不知道Customer
类型)。
如何访问客户列表以访问Customer'a属性,而不必显式引用.dll?
您有三种选择
Client
接口Client
工具移至或移至第三个dll,反射的DLL和您的控制台应用程序都可以引用该文件。dynamic
关键字作为对象(dynamic customerList = methodInfo.Invoke(...
)的类型,这正是它被发明的目的。IEnumerable
并使用反射调用在返回对象Client
上调用方法。object
IEnumerable
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句