Return Generic Type after determining Type Parameter dynamically

前端 未结 2 1940
攒了一身酷
攒了一身酷 2021-01-29 04:40

I have a generic class as shown below

public class MyClass
{
    public T MyProp { get; set; }
}

Now I want to return the instance of

2条回答
  •  野性不改
    2021-01-29 05:24

    What you are trying to do is not possible. While you can create a generic type for an arbitrary generic type argument at runtime like this

    public MyClass ReturnWithDynamicParameterType(Type genericArgument)
    {
        Type genericType = typeof(MyClass<>).MakeGenericType(genericArgument);
        return (MyClass)Activator.CreateInstance(genericType);
    }
    
    
    

    this return line will always throw an InvalidCastException. As Lee already commented, classes are invariant. This means that for example MyClass and MyClass are simply not the same types. They are not even inherited from one another.

    Even co-variance won't help since the out keyword is not allowed for generic parameters in classes.

    I don't see a solution for this without knowing the types at compile-time. But I'm sure that you can solve what you are actually trying to achieve by other methods.

    提交回复
    热议问题