我正在努力实现这一点,不知道它是否可行但是...... 这是一个代码示例:
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));
}
答案 0 :(得分:3)
您应该创建一个接受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);
答案 1 :(得分:1)
如果你想在泛型中使用反射,也许它会帮助你看到下面的代码:
Type type1 = tuple.Item1.GetType();
MethodInfo method = typeof(PlateformeHelper).GetMethod("GetPlateforme");
MethodInfo generic = method.MakeGenericMethod(type1);
generic.Invoke(null, null);
了解更多信息MakeGenericMethod
希望有用XD。