Get property of generic class

后端 未结 5 995
孤城傲影
孤城傲影 2020-12-03 09:26

I have a generic class, and an object value where obj.GetType().GetGenericTypeDefinition() == typeof(Foo<>).

class Foo
{
    publ         


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-03 10:16

    You should be able to use:

    Type t = obj.GetType();
    
    PropertyInfo prop = t.GetProperty("Items");
    
    object list = prop.GetValue(obj);
    

    You will not be able to cast as a List directly, of course, as you don't know the type T, but you should still be able to get the value of Items.


    Edit:

    The following is a complete example, to demonstrate this working:

    // Define other methods and classes here
    class Foo
    {
        public List Items { get; set; }
    }
    
    class Program
    {
        void Main()
        {   
            //just to demonstrate where this comes from
            Foo fooObject = new Foo();
            fooObject.Items = new List { 1, 2, 3};
            object obj = (object)fooObject;
    
            //now trying to get the Item value back from obj
            //assume I have no idea what  is
            PropertyInfo propInfo = obj.GetType().GetProperty("Items"); //this returns null
            object itemValue = propInfo.GetValue(obj, null);
    
            Console.WriteLine(itemValue);
                        // Does not print out NULL - prints out System.Collections.Generic.List`1[System.Int32]
    
    
            IList values = (IList)itemValue;
            foreach(var val in values)
                Console.WriteLine(val); // Writes out values appropriately
        }
    }
    

提交回复
热议问题