开发者

Extension methods don't work on subclasses?

开发者 https://www.devze.com 2023-01-17 11:03 出处:网络
Apparently, extension methods don\'t work on subclasses, or is it just me? private class Parent { } private class Child

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

精彩评论

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