我以泛型類型開始,並且堅持使用我的項目。也許我不太瞭解泛型。解釋已經插入。基本上,我需要實現DO()方法,但我不知道如何解決<T2>:將泛型類型轉換爲子類型
public abstract class MyGenericClass<T> { }
public class MyGenericClass<T, T2> : MyGenericClass<T>
{
public Expression<Func<T, T2>> expression;
public MyGenericClass(Expression<Func<T, T2>> expression)
{
this.expression = expression;
}
}
public class MyClass<T>
{
// I need to mantain a list of my generic class for later use.
// I don't know T2 at this point.
// So I Chose to use Inheritance as a workaround (MyGenericClass<T> and MyGenericClass<T, T2>).
// Maybe it's not a good solution but I counldn't find out other solution.
public List<MyGenericClass<T>> MyGenericList = new List<MyGenericClass<T>>();
// I receive the parametric argument T2 here as part of an Expresion.
// And I keep the expression in my list.
public MyGenericClass<T, T2> ReceivingMethod<T2>(Expression<Func<T, T2>> expression)
{
MyGenericClass<T, T2> genericImp = new MyGenericClass<T, T2>(expression);
MyGenericList.Add(genericImp);
return genericImp;
}
}
public class Client<T>
{
MyClass<T> class1;
// class1 has been created and his field MyGenericList has beed populated.
// Then when I call Do()....
public void Do()
{
foreach (var item in class1.MyGenericList)
{
// ...I need something like this here,
// but it does not compile because I don't know T2 here.
// The caller of Do() method doesn't know T2.
MyGenericClass<T, T2> myGenericItem = (MyGenericClass<T, T2>)item;
var a = myGenericItem.expression;
}
}
}
你有沒有考慮過使用
此時您必須使用反射。或者真的試圖找出不同的設計。泛型旨在讓您編寫大多數與類型無關的代碼,而不是讓您將許多不同類型組合在一起。 – juharr
'Do'會如何使用'myGenericItem'?如果它不需要做特定於'T2'的任何事情,那麼你可以在派生類中實現的'MyGenericClass'上定義抽象方法,並由'Do'調用。 –
KMoussa