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.
精彩评论