簡體   English   中英

在通用方法中傳遞對象類型

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM