Get property of generic class

后端 未结 5 990
孤城傲影
孤城傲影 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:11

    @ReedCopsey is absolutely correct, but in case you're really asking the question "How do I fish out the generic details of a type?", here's some "Fun with Reflection":

    public void WhatsaFoo(object obj)
    {
        var genericType = obj.GetType().GetGenericTypeDefinition();
        if(genericType == typeof(Foo<>))
        {
            // Figure out what generic args were used to make this thing
            var genArgs = obj.GetType().GetGenericArguments();
    
            // fetch the actual typed variant of Foo
            var typedVariant = genericType.MakeGenericType(genArgs);
    
            // alternatively, we can say what the type of T is...
            var typeofT = obj.GetType().GetGenericArguments().First();
    
            // or fetch the list...
            var itemsOf = typedVariant.GetProperty("Items").GetValue(obj, null);
        }
    }
    

提交回复
热议问题