[英]Passing object type in generic method
我正在尝试实现这一目标,但不知道是否可行。这是一个代码示例:
public List<Tuple<AbstractPlateforme, AbstractPlateforme>> tuple;
Type type1 = tuple.Item1.GetType();
//This line gives me error: Error CS0118 'type1' is a variable but is used like a type
var plateforme = PlateformeHelper.GetPlateforme<type1>();
//This is my method from my PlateformeHelper class which returns an instance of an instantiated object of the same type (the list may only contain 1 object of that type which inherit from AbstractPlateforme)
public static T GetPlateforme<T>() where T : AbstractPlateforme
{
return (T)ListePlateforme.Find(x => x.GetType() == typeof (T));
}
您应该创建一个接受Type
参数而不是泛型的重载:
public static AbstractPlateforme GetPlateforme(Type type)
{
return (AbstractPlateforme)ListePlateforme.Find(x => x.GetType() == type);
}
public static T GetPlateforme<T>() where T : AbstractPlateforme
{
return (T)GetPlateforme(typeof(T));
}
然后您可以简单地调用新的重载:
var plateforme = PlateformeHelper.GetPlateforme(type1);
如果您想将反射与泛型一起使用,也许可以帮助您查看下面的代码:
Type type1 = tuple.Item1.GetType();
MethodInfo method = typeof(PlateformeHelper).GetMethod("GetPlateforme");
MethodInfo generic = method.MakeGenericMethod(type1);
generic.Invoke(null, null);
有关更多信息MakeGenericMethod
希望是有用的XD。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.