我以泛型类型开始,并且坚持使用我的项目。也许我不太了解泛型。解释已经插入。基本上,我需要实现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