[英]Setting a generic type parameter from a method parameter
有什么办法可以做这样的事情吗?
void SomeMethod(Type generic)
{
SomeGenericMethod<generic>();
}
我需要将类型作为“常规”参数而不是通用类型参数传递。
您可以通过反射来做到这一点:
public class foo
{
public void SomeMethod(Type type)
{
var methodInfo = this.GetType().GetMethod("SomeGenericMethod");
var method = methodInfo.MakeGenericMethod(new[] { type });
method.Invoke(this, null);
}
public void SomeGenericMethod<T>()
{
Debug.WriteLine(typeof(T).FullName);
}
}
class Program
{
static void Main(string[] args)
{
var foo = new foo();
foo.SomeMethod(typeof(string));
foo.SomeMethod(typeof(foo));
}
}
就是说,以这种方式使用反射意味着您一开始就失去了使用泛型的某些好处,因此您可能想看看其他设计替代方案。
假设您的方法是在名为MyClass的类中定义的,则应这样做:
var MyObject = new MyClass();
typeof(MyClass).GetMethod("SomeGenericMethod").MakeGenericMethod(generic).Invoke(myObject, null);
Type.GetMethod()获取一个对象,该对象描述了在其调用的Type中定义的方法。 该方法是通用的,因此我们需要调用MakeGenericMethod,并传递其一个通用参数。
然后,我们调用该方法,传递要调用该方法的对象以及它需要的所有参数。 由于不带参数,因此我们只传递null。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.