ジェネリック クラスとオブジェクト値 where obj.GetType().GetGenericTypeDefinition() == typeof(Foo<>)
.
class Foo<T>
{
public List<T> Items { get; set; }
}
Items
fromの値を取得するにはどうすればよいobj
ですか? obj
が であることを忘れないでください。が何であるかがわからないため、 as としてObject
キャストすることはできません。obj
Foo
T
これにリフレクションを使用したいと思っていましたが、毎回GetProperty("Items")
nullを返します。ただし、誰かがこれを熟考せずに行う良い方法を知っている場合は、ぜひ。
私のコードが次のようになっているとしましょう:
//just to demonstrate where this comes from
Foo<int> fooObject = new Foo<int>();
fooObject.Items = someList;
object obj = (object)fooObject;
//now trying to get the Item value back from obj
//assume I have no idea what <T> is
PropertyInfo propInfo = obj.GetType().GetProperty("Items"); //this returns null
object itemValue = propInfo.GetValue(obj, null); //and this breaks because it's null