我是反射和依赖注入概念的新手,为了更好地理解,我开始运行一些代码。
我试图从包含 T 对象的泛型类的方法中调用类 T 的非泛型方法。
考虑以下示例代码,当我运行它时,我得到了这个:
System.InvalidOperationException:Void DisplayProperty() 不是 GenericMethodDefinition。MakeGenericMethod 只能在 MethodBase.IsGenericMethodDefinition 为 true 的方法上调用。
我做错了什么?
using System;
using System.Collections.Generic;
using System.Reflection;
namespace di001
{
class MyDependency
{
private String _property;
public String Property
{
get => _property;
set => _property = value;
}
public void DisplayProperty()
{
Console.WriteLine(Property);
}
}
class DIClass<T>
{
public T obj;
public void DisplayMessage()
{
MethodInfo method = typeof(T).GetMethod("DisplayProperty");
MethodInfo generic = method.MakeGenericMethod(typeof(T));
generic.Invoke(this, null);
}
public DIClass(T obj)
{
this.obj = obj;
}
}
class Program
{
static void Main(string[] args)
{
DIClass<MyDependency> x = new DIClass<MyDependency>(new MyDependency());
x.DisplayMessage();
}
}
}
线
MethodInfo generic = method.MakeGenericMethod(typeof(T));
根本没有必要。
在这一点上,当实际执行时,T
它不是泛型的,因为它已经被构造(T
是你想要的实际类型)。method
无论如何肯定不是通用方法。
你应该能够做到
typeof(T).GetMethod("DisplayProperty").Invoke(...
我也想象你想Invoke
用参数调用(obj, null)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句