对于预期操作不起作用通用约束

编程入门 行业动态 更新时间:2024-10-12 18:16:03
本文介绍了对于预期操作不起作用通用约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一些无法理解,为什么下面的代码片段并没有给我一个错误

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.

更多推荐

对于预期操作不起作用通用约束

本文发布于:2023-11-23 01:14:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1619578.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不起作用   操作

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!