[英]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
{
}
I have already checked out this question How do I make the return type of a method generic? 我已经检查了这个问题, 如何使方法的返回类型通用? . 。 Is there something more elegant than Convert.ChangeType()? 有没有比Convert.ChangeType()更优雅的东西?
Why is it not possible to return an instance of Soccer or Football when there is a constraint on the type? 当类型受约束时,为什么不能返回Soccer或Football的实例?
If you expect different implementations based on the exact type of the generic, you're not actually dealing with a generic any more. 如果您希望根据泛型的确切类型实现不同的实现,则实际上不再需要处理泛型。
You should define two classes, eg FootBallManager : Manager<IFootball>
and SoccerManager : Manager<ISoccer>
您应该定义两个类,例如FootBallManager : Manager<IFootball>
和SoccerManager : Manager<ISoccer>
Based on your update, what you actually want is an additonal constraint on your generic of new()
and to implement your class as 根据您的更新,您真正想要的是对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
{
}
You just need a class constraint and as T 您只需要一个类约束并且作为T
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.