开发者

Extension methods don't work on subclasses?

Apparently, extension methods don't work on subclasses, or is it just me?

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

There is a typo in this question (开发者_Python百科which I'm leaving so that the rest makes sense) - I forgot to make Child inherit from Parent.

As it happens, my real problem was that I didn't have the appropriate using statement.

(Unfortunately, I can't delete, as too many upvotes on answer.)


This should work just fine (LINQ extensions are built on top of IEnumerable<T>, and they work on List<T> et al.). The issue is that Child does not inherit from Parent in your example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜