简体   繁体   中英

C#: Adding extension methods to a base class so that they appear in derived classes

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

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

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?

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.

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

An extension method will actually apply to all inheritors/implementors of the type that's being extended (in this case, Control). You might try checking your using statements to ensure the namespace that the extension method is in is being referenced where you're trying to call it.

Note that if you call an extension method from a property in class which inherits from a base class that has the extension method applied to it, you have to suffix the extension method with this

eg

public int Value
{
    get => this.GetValue<int>(ValueProperty);
    set => SetValue(ValueProperty, value);
}

Where GetValue is my extension method applied to the base class.

您还可以确保未在命名空间中定义扩展,然后引用它们的任何项目都将自动导入它们。

I think you have to make the extension generic:

public static void ExampleMethod<T>(this T ctrl)
    where T : Control 
{ /* ... */ }

No, you don't have to.. it should also work with the non-generic version you posted, remember to add the namespace for your extensions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM