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

c# – 扩展方法不适用于子类?

发布时间:2020-12-16 01:38:11 所属栏目:百科 来源:网络整理
导读:显然,扩展方法不适用于子类,还是仅仅是我? private class Parent{ }private class Child{}public static class Extensions{ public static void Method(this Parent parent) { }}//Test codevar p = new Parent();p.Method(); // --- compiler likevar c =
显然,扩展方法不适用于子类,还是仅仅是我?

private class Parent
{        
}

private class Child
{
}

public static class Extensions
{
    public static void Method(this Parent parent)
    {
    }
}

//Test code
var p = new Parent();
p.Method();            // <--- compiler like
var c = new Child();
c.Method();            // <--- compiler no like

UPDATE

在这个问题上有一个拼写错误(我要离开,以便其余的有意义) – 我忘了让Child从Parent继承.

碰巧,我真正的问题是我没有适当的使用声明.

(不幸的是,我无法删除,因为答案太多了.)

解决方法

这应该可以正常工作(LINQ扩展构建在IEnumerable< T>之上,并且它们可以在List< T>等等上工作).问题是Child在您的示例中不从Parent继承.

(编辑:李大同)

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

    推荐文章
      热点阅读