c# – 代表逆转(参数兼容性)

c# – 代表逆转(参数兼容性),第1张

概述我正在查看Nut shell文本中的C#5,有关委托参数兼容性的部分.它说 When you call a method, you can supply arguments that have more specific types than the parameters of that method. This is ordinary polymorphic behavior. For exac 我正在查看Nut shell文本中的C#5,有关委托参数兼容性的部分.它说

When you call a method,you can supply arguments that have more specific types than the parameters of that method. This is ordinary polymorphic behavior. For exactly the same reason,a delegate can have more specific parameter types than its method target. This is called contravariance.

直到最后一句话,这一段才有意义.为什么它是逆变,即这里的预测是逆变?

随附的例子如下.

delegate voID StringAction (string s);class Test{    static voID Main()    {        StringAction sa = new StringAction (ActOnObject);        sa ("hello");    }    static voID ActOnObject (object o)    {        Console.Writeline (o); // hello    }}
解决方法 对象(函数ActionObject的参数)到为委托(字符串)声明的类型的投影是逆变的.

这是允许的,因为通过传递一个字符串(你必须由委托签名),你可以保证你有一个对象(分配的函数需要),所以一切都很好,安全.

你知道,在这种情况下,“普通多态”实际上称为协方差.

有关详细信息,请参见MSDN.

总结

以上是内存溢出为你收集整理的c# – 代表逆转(参数兼容性)全部内容,希望文章能够帮你解决c# – 代表逆转(参数兼容性)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/langs/1219252.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存