0
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
{
}

我已经检查过这个问题How do I make the return type of a method of a generic? . 还有什么比 Convert.ChangeType() 更优雅的吗?

当对类型有限制时,为什么不能返回 Soccer 或 Football 的实例?

4

2 回答 2

5

如果您期望基于泛型的确切类型有不同的实现,那么您实际上不再处理泛型。

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

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

public class Manager<T> where T: IBallGame, new()
{
    T GetManager()
    {
         return new T();         
    }
}
于 2013-09-24T02:24:10.480 回答
2
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

于 2013-09-24T02:36:11.807 回答