ジェネリック型から始めています。私は自分のプロジェクトに悩まされています。たぶん私はジェネリック医薬品をとてもよく理解していなかったでしょう。説明がインラインで挿入されています。基本的に私は、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
'' MyGenericItem'をどのように使用するのですか? 'T2'に固有のことをする必要がなければ、' MyGenericClass 'に派生クラスで実装され、' Do'によって呼び出される抽象メソッドを定義することができます –
KMoussa