2013-09-24 130 views
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 generic?。有没有比Convert.ChangeType()更优雅的东西?在c中返回泛型类型#

为什么在类型有限制时不能返回足球或足球的实例?

+2

我认为因为足球和足球需要满足两个接口才能符合经理级声明,而不只是一个或另一个。 –

+0

@ValentinKuzub:为什么呢?我基本上将两个Manger类合并为一个。如果没有这个,将会有两个类SoccerManager和FootballManger,每个都有一个方法GetInstance。如果检查T的类型被认为是不好的编码,那么泛型类的目的是相当有限的,你不觉得吗? – bobbyalex

+0

你认为'List '是有限的吗?它是否需要检查'T'的类型来完成它的工作?泛型类的意义在于,只要T符合通用类的约束,类的方法的实现就可以保持,而不管T的类型如何。在你的情况下,'GetManager'的实现取决于'T'的类型。如果你真的是RY,你只能违反DRY。 –

回答

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

你只需要一个约束和as T

+0

这不会工作,这是整个问题。你会得到一个编译时错误,说'不能将足球转换为T' – bobbyalex

+0

适用于我,笔记类约束和T –

+0

该评论是在你编辑之前。这工作:) – bobbyalex

5

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

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

根据您的更新,你真正想要的是你的通用的new()并产生额外的约束来实现您的类作为

public class Manager<T> where T: IBallGame, new() 
{ 
    T GetManager() 
    { 
     return new T();   
    } 
} 
+0

@ValentinKuzub:我已经更新了这个问题。 – bobbyalex

+0

谢谢,现在看起来好多了 –

+0

原帖来自post刚刚不会在这里编译新管理器();原因ISoccer不适合新的()约束 –