繁体   English   中英

在C#中返回泛型类型

[英]Returning generic types in c#

public class Manager<T> where T: IBallGame
{
T GetManager()
{
//if T is ISoccer return new Soccer()
//if T is IFootball return new Football()

//This wont work. Why?
if (typeof(T) == typeof(ISoccer))
                return new Soccer();
}
}

Interface ISoccer: IBallgame
{
}
class Soccer: ISoccer
{
}
Interface IFootball: IBallgame
{
}
class Football:IFootball
{
}

我已经检查了这个问题, 如何使方法的返回类型通用? 有没有比Convert.ChangeType()更优雅的东西?

当类型受约束时,为什么不能返回Soccer或Football的实例?

如果您希望根据泛型的确切类型实现不同的实现,则实际上不再需要处理泛型。

您应该定义两个类,例如FootBallManager : Manager<IFootball>SoccerManager : Manager<ISoccer>

根据您的更新,您真正想要的是对new()泛型的附加约束,并将您的类实现为

public class Manager<T> where T: IBallGame, new()
{
    T GetManager()
    {
         return new T();         
    }
}
public class Manager<T> where T : class, IBallgame
{
    T GetManager()
    {
        //if T is ISoccer return new Soccer()
        //if T is IFootball return new Football()


        if (typeof(T) == typeof(ISoccer))
            return new Soccer() as T;

        //code
    }
}

public interface IBallgame
{

}
public interface ISoccer : IBallgame
{
}
public class Soccer : ISoccer
{
}
public interface IFootball : IBallgame
{
}
class Football : IFootball
{
}

您只需要一个约束并且作为T

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM