开发者

How to get generic type from object type

开发者 https://www.devze.com 2023-02-15 07:13 出处:网络
My Classes are; class BaseClass { } class DerivedClass1 : BaseClass { } class GenericClass<T> { } class DerivedClass2 : BaseClass

My Classes are;

class BaseClass
{

}

class DerivedClass1 : BaseClass
{

}

class GenericClass<T>
{

}

class DerivedClass2 : BaseClass
{
    GenericClass<DerivedClass1> subItem;
}

I want to access all fields of DerivedClass2 class. I use System.Reflection and FieldInfo.GetValue() method;

Bu I cant get subItem field. FieldInfo.GetValue() method return type is "object". And I cant cast to GenericClass<DerivedClass1> or I cant get DerivedClass1 type. I try this with BaseClass

BaseClass instance = FieldInfo.Getvalue(this) as GenericClass<BaseClass>;

but instance is null. How to get instance with type or how to get only开发者_开发百科 type?


I'm not sure exactly what you want to achieve, but his works for me:

var foo = new DerivedClass2();
var result = typeof(DerivedClass2).GetField("subItem", 
                                            BindingFlags.NonPublic | 
                                            BindingFlags.Instance)
                                  .GetValue(foo);
var genericClassField = result as GenericClass<DerivedClass1>;

genericClassField is of type GenericClass<DerivedClass1> - of course you have to assign it a value before doing this, otherwise result will be null, for this I added a constructor to your DerivedClass2 that does just that:

class DerivedClass2 : BaseClass
{
    GenericClass<DerivedClass1> subItem;

    public DerivedClass2()
    {
        subItem = new GenericClass<DerivedClass1>();
    }
}

Edit:

To find out the type of result at runtime you could do the following:

var foo = new DerivedClass2();
var result = typeof(DerivedClass2).GetField("subItem", 
                                            BindingFlags.NonPublic | 
                                            BindingFlags.Instance)
                                  .GetValue(foo);
Type myType = result.GetType().GetGenericArguments()[0];

In the example this would return the type DerivedClass1. Also I think this msdn article might be relevant.

0

精彩评论

暂无评论...
验证码 换一张
取 消