Return Generic Type after determining Type Parameter dynamically

前端 未结 2 1905
攒了一身酷
攒了一身酷 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<object> ReturnWithDynamicParameterType(Type genericArgument)
    {
        Type genericType = typeof(MyClass<>).MakeGenericType(genericArgument);
        return (MyClass<object>)Activator.CreateInstance(genericType);
    }
    

    this return line will always throw an InvalidCastException. As Lee already commented, classes are invariant. This means that for example MyClass<object> and MyClass<string> 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.

    0 讨论(0)
  • 2021-01-29 05:26

    I am not sure if this fits your use, but your only way out is the use of an interface that is covariant.

    public interface IMyClass<out T>
    {
        T MyProp { get; }
    }
    
    public class MyClass<T> : IMyClass<T>
    {
        public T MyProp { get; set; }
    }
    
    public IMyClass<object> ReturnWithDynamicParameterType()
    {
        //This function determines the type of T at runtime and should return instance of MyClass<T>
    
        return new MyClass<string>();
    }
    

    This code compiles because your return type is not a class, but a covariant interface (note the out T on the type parameter). That interface allows retrieval only, so the get;set on the property has been replaced by a get on the interface.

    0 讨论(0)
提交回复
热议问题