扩展方法不适用于子类?
显然,扩展方法不适用于子类,或者只是我?
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
更新
这个问题中有一个拼写错误(我将其保留,以便其余部分有意义) - 我忘记让Child
继承Parent
。
碰巧,我真正的问题是我没有适当的 using
语句。
(不幸的是,我无法删除,因为对答案的点赞太多。)
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 (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.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这应该可以正常工作(LINQ 扩展构建在
IEnumerable
之上,并且它们可以在List
等上工作)。问题是在您的示例中Child
不继承自Parent
。This should work just fine (LINQ extensions are built on top of
IEnumerable<T>
, and they work onList<T>
et al.). The issue is thatChild
does not inherit fromParent
in your example.