如何从泛型 class 的方法调用 class T 的非泛型方法?
How to call a non-generic method of a class T from a method of a generic class?
我是反射和依赖注入概念的新手,我开始运行一些代码以便更好地理解。
我正在尝试从包含 T 对象的泛型 class 的方法调用 class T 的非泛型方法。
考虑以下示例代码,当我 运行 它时,我得到了这个:
System.InvalidOperationException: Void DisplayProperty() is not a
GenericMethodDefinition. MakeGenericMethod may only be called on a
method for which MethodBase.IsGenericMethodDefinition is 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(...
我还想你想用参数 (obj, null)
调用 Invoke
我是反射和依赖注入概念的新手,我开始运行一些代码以便更好地理解。
我正在尝试从包含 T 对象的泛型 class 的方法调用 class T 的非泛型方法。
考虑以下示例代码,当我 运行 它时,我得到了这个:
System.InvalidOperationException: Void DisplayProperty() is not a GenericMethodDefinition. MakeGenericMethod may only be called on a method for which MethodBase.IsGenericMethodDefinition is 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(...
我还想你想用参数 (obj, null)
Invoke