问题描述
我有一些无法理解,为什么下面的代码片段并没有给我一个错误
I am having some trouble understanding why the following snippet does not give me an error
public void SomeMethod<T>(T arg) where T : MyInterface
{
MyInterface e = arg;
}
不过,这一次,我希望由于工作的泛型类型约束
But this one, which I would expect to work due to the generic type constraint
private readonly IList<Action<MyInterface>> myActionList = new List<Action<MyInterface>>();
public IDisposable Subscribe<T>(Action<T> callback) where T: MyInterface
{
myActionList.Add(callback); // doesn't compile
return null
}
给出了这样的错误
Gives this error
cannot convert from 'System.Action<T>' to 'System.Action<MyInterface>'
我使用VS2012 SP1和.NET 4.5。
I am using VS2012 sp1 and .NET 4.5.
任何人都可以解释为什么限制不允许这种编译?
Can anyone explain why the constraint does not allow this to compile?
推荐答案
类和代表们不一样的东西。 System.Action&LT; MyInterface的&GT;
重$ P $类型的单个参数psents功能 MyInterface的
,而 System.Action&LT; T&GT;
重presents的方法与类型 T:MyInterface的。该函数签名不兼容,它不相应和的 T
是 MyInterface的
的衍生物,签名就只能是兼容如果 T
正是 MyInterface的
。
Classes and delegates are not the same thing. System.Action<MyInterface>
represents a function with a single parameter of type MyInterface
whilst System.Action<T>
represents a method with a parameter of type T : MyInterface
. The function signatures are not compatible, it is not relevent that T
is a derivative of MyInterface
, the signature would only be compatible if T
was exactly MyInterface
.
这篇关于对于预期操作不起作用通用约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!