加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 02:03:18 所属栏目:百科 来源:网络整理
导读:我正在查看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 reas
我正在查看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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读