C# 在泛型方法中传递对象类型

C# 在泛型方法中传递对象类型,c#,generics,reflection,C#,Generics,Reflection,我正在努力实现这一目标,但不知道这是否可行。。 下面是一个代码示例: 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 platefo

我正在努力实现这一目标,但不知道这是否可行。。 下面是一个代码示例:

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 type1=tuple.Item1.GetType();
//这一行给了我一个错误:error CS0118'type1'是一个变量,但它的用法与类型类似
var plateforme=PlateformeHelper.GetPlateforme();
//这是我的PlatformeHelper类中的方法,它返回相同类型的实例化对象的实例(列表中只能包含1个从AbstractPlatforme继承的该类型的对象)
公共静态T GetPlateforme(),其中T:AbstractPlateforme
{
return(T)listplateforme.Find(x=>x.GetType()==typeof(T));
}

如果您想在泛型中使用反射,也许它可以帮助您查看下面的代码:

    Type type1 = tuple.Item1.GetType();    
    MethodInfo method = typeof(PlateformeHelper).GetMethod("GetPlateforme");
    MethodInfo generic = method.MakeGenericMethod(type1);
    generic.Invoke(null, null);
更多信息


希望有用XD。

您应该创建一个重载,该重载接受
类型
参数,而不是泛型参数:

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));
}

太抽象了,你想实现什么?为什么
ListPlatforme
存储不同的类型?我需要存储不同类型的AbstractPlatforme子类,以便获得每个类的特定信息并从其他类访问它们。您的代码有语法错误,首先修复它:第1行中的tuple是一个列表,而第2行中的列表没有Item1。@mecek我有一个tuple列表,在我的tuple中有2个itemstuple在代码中不是一个tuple,这是一个列表。我要添加的唯一一件事是,由于非泛型方法返回一个
对象,因此调用后需要强制转换。是的,嗯,如果他有类型并且可以强制转换为它,他也可以调用泛型版本。您只能强制转换为实际类型,如果需要的话,如果不使用反射,您无法轻松地强制转换为变量或表达式中包含的类型。如果您没有编写依赖于X类型的代码,那么很可能您没有利用X提供的任何东西,或者他也必须将调用代码编写为泛型。同意-在大多数情况下,混合反射和泛型是一件痛苦的事情,更不用说在涉及强制转换时了。我更喜欢你的编辑,而不是在客户端+1.
var plateforme = PlateformeHelper.GetPlateforme(type1);