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

[亡魂溺海] 提交于 2019-12-04 02:46:17

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 (e.g. 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

e.g.

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

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

You can also make sure your extensions aren't defined in a namespace, then any project that references them will auto-import them.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!