リフレクションを使用して、「MyTypes」の各リストを T:MyDataObject の制約を持つジェネリック メソッドに渡すにはどうすればよいですか?
public interface IAllMyTypes
{
List<FirstType> MyType1 { get; set; }
List<SecondType> MyType2 { get; set; }
List<ThirdType> MyType3 { get; set; }
}
FirstType、SecondType、および ThirdType は MyDataObject から継承しますが (以下に示すように)、異なるプロパティを持ちます。
public class FirstType : MyDataObject
{
//various properties
}
このシグネチャを使用してデータをメソッドに渡すことができませんでした:
void DoSomething<T>(IEnumerable<T> enumerable) where T : MyDataObject;
エラーは、「型引数を推論できません」というものです。
これが私の失敗した試みです:
public void DoSomethingWithAllMyTypes(IAllMyTypes allMyTypes)
{
foreach (PropertyInfo propertyInfo in allMyTypes.GetType().GetProperties())
{
var x = propertyInfo.GetValue(allMyTypes) as IList;//im not sure what to do here
if(x==null) throw new Exception("still wrong");
DoSomething(x);
}
}
次のようなプロパティを直接指定すると、DoSomething(..) のすべてのコードが正しく機能します。
public void DoSomethingWithAllMyTypes(IAllMyTypes allMyTypes)
{
DoSomething(allMyTypes.MyType1);
DoSomething(allMyTypes.MyType2);
DoSomething(allMyTypes.MyType3);
}