我想在使用反射(查找接口实现)找到它之后,在使用泛型类型的类上动态执行方法。
下面是我陷入困境的一个例子。非常感谢您的帮助。
Setup
public interface IActionRequired<T> where T : class {
void DoThis(T[] receivedObjects);
}
public class BookDetails {
public int BookId { get; set; }
public string BookName { get; set; }
}
public class LibraryBookReturned : IActionRequired<BookDetails>
{
public void DoThis(BookDetails[] receivedObjects)
{
foreach(var book in receivedObjects)
System.Console.WriteLine(book.BookName);
}
}
使用反射的示例尝试
下面,我仅使用第一个实现,但在现实世界中,我将使用命名约定来查找正确的实现。
var assembly = Assembly.GetCallingAssembly();
var listOfImplementations =
GetAllTypesImplementingOpenGenericType(typeof(IActionRequired<>), assembly);
var implementation = listOfImplementations.FirstOrDefault();
var implementationUsesInterface = implementation.GetInterfaces() [0];
var interfaceUsesType = implementationUsesInterface.GetGenericArguments() [0];
我知道下面的内容不起作用(我收到一条错误消息,说 interfaceUsesType 是变量而不是类型),但它表明了我想要执行的操作:
var instance =
assembly.CreateInstance(implementation.FullName) as IActionRequired<interfaceUsesType>;
var results = this.CheckForMessages<interfaceUsesType>();
instance.DoThis(results);
您将必须发出通用方法的运行时类型特定版本。看看MethodInfo.MakeGenericMethod https://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.makegenericmethod为了那个。
MakeGenericMethod 方法允许您编写将特定类型分配给泛型方法定义的类型参数的代码,从而创建表示特定构造方法的 MethodInfo 对象。如果此 MethodInfo 对象的 ContainsGenericParameters 属性返回 true,则可以使用它来调用该方法或创建委托来调用该方法。
简而言之(伪)代码:
this.GetType()
.GetMethod("CheckForMessages")
.MakeGenericMethod(interfaceUsesType)
.Invoke(this, null);
您还可以在这里阅读:如何:使用运行时类型调用泛型方法 https://www.rickvandenbosch.net/blog/how-to-call-a-generic-method-with-a-runtime-type/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)