C# method generic return type casting

前端 未结 3 407
悲哀的现实
悲哀的现实 2020-12-10 15:32

I am trying to create a method in an interface with a generic return type but I fail to cast the generic to a specific type/class. But if I put the generic on the interface

3条回答
  •  一生所求
    2020-12-10 15:55

    If you need your interface to support an arbitrary set of classes, and what classes are used is determined by the caller then something like this is the most general solution.

    public class Bar : IFoo {
        T foo() { 
            if (typeof(T)==typeof(Rain))
               return new Rain() as T;
            if (typeof(T)==typeof(Snow))
               return new Snow() as T;
            Throw new ArgumentException("Not implemented for " + typeof(T).Name);
        }
    }
    

    If all your T's have a common interface and that is what you are interested in you could do;

    public class Snow : IWeather {...}
    public class Rain: IWeather {...}
    public class Bar : IFoo {
        IWeather  foo() T : IWeather { 
            if (typeof(T)==typeof(Rain))
               return new Rain();
            if (typeof(T)==typeof(Snow))
               return new Snow();
            Throw new ArgumentException("Not implemented for " + typeof(T).Name);
        }
    }
    

提交回复
热议问题