Return Generic Type after determining Type Parameter dynamically

前端 未结 2 1906
攒了一身酷
攒了一身酷 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: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
    {
        T MyProp { get; }
    }
    
    public class MyClass : IMyClass
    {
        public T MyProp { get; set; }
    }
    
    public IMyClass ReturnWithDynamicParameterType()
    {
        //This function determines the type of T at runtime and should return instance of MyClass
    
        return new MyClass();
    }
    
    
    

    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.

    提交回复
    热议问题