我目前在 System.Windows.Forms.Control 上有一个扩展方法,如下所示:
public static void ExampleMethod(this Control ctrl){ /* ... */ }
但是,此方法不会出现在从 Control 派生的类中,例如 PictureBox。我可以创建一个扩展方法,它不仅出现在 Control 中,而且出现在从 Control 派生的类中,而无需进行显式转换吗?
最佳答案
您必须为定义扩展类的命名空间包含 using 语句,否则扩展方法将不在范围内。
扩展方法在派生类型上工作良好(例如,在 System.Linq 的 IEnumerable<T>
上定义的扩展方法)。
关于C#:将扩展方法添加到基类,以便它们出现在派生类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1217591/