C#:将扩展方法添加到基类中,以便它们出现在派生类中 [英] C#: Adding extension methods to a base class so that they appear in derived classes

查看:168
本文介绍了C#:将扩展方法添加到基类中,以便它们出现在派生类中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在System.Windows.Forms.Control上有一个扩展方法,如下所示:

I currently have an extension method on System.Windows.Forms.Control like this:

public static void ExampleMethod(this Control ctrl){ /* ... */ }

但是,此方法不会出现在从Control派生的类上,例如PictureBox.是否可以使扩展方法不仅出现在Control中,而且出现在从Control派生的类中,而不必进行显式强制转换?

However, this method doesn't appear on classes derived from Control, such as PictureBox. Can I make an extension method that appears not only in Control, but for classes derived from Control, without having to do an explicit cast?

推荐答案

对于定义扩展类的名称空间,必须包含using语句,否则扩展方法将不在范围内.

You must include the using statement for the namespace in which your extensions class is defined or the extension methods will not be in scope.

扩展方法可以很好地处理派生类型(例如,在System.Linq中的IEnumerable<T>上定义的扩展方法).

Extension methods work fine on derived types (e.g. the extension methods defined on IEnumerable<T> in System.Linq).

这篇关于C#:将扩展方法添加到基类中,以便它们出现在派生类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆