在泛型方法中传递对象类型
本文关键字:对象 类型 泛型方法 | 更新日期: 2023-09-27 18:26:22
我正在努力实现这一点,但不知道它是否可行。。这是一个代码示例:
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有用。