【发布时间】:2012-10-18 06:18:42
【问题描述】:
我有这个:
public IClub GetTeam()
{
return new Arsenal();
}
//compiles since Arsenal is an IClub
public T GetTeam<T>() where T : IClub, new()
{
return new Arsenal();
}
//wouldn't compile saying "cannot convert Arsenal to T"
但这些东西有效:
public T GetTeam<T>() where T : IClub, new()
{
T t = new T();
t.Sponsor = "Nike"; //since it knows T is IClub,
return new T(); //but why the injustice to return type alone?
}
为什么即使返回类型是
IClub,第二个代码块也不能编译?这不是不公平吗?我知道我没有充分利用上述代码中类型约束的潜力,但有什么替代方法可以让代码运行?
【问题讨论】:
-
为什么不返回 IClub? public IClub GetTeam
() where T : IClub, new(). -
@AmitMittal 这类似于问我为什么不使用第一个代码块。我的设计就是为此而迫不及待。我的意思是像阿森纳这样的所有俱乐部都继承了 IClub,上面定义了
GetTeam<T>。我知道这不是一个好的设计。我会重新考虑一下
标签: c# type-inference return-type generic-constraints