C#是否可以向超类添加方法

use*_*110 0 c# xamarin.forms

在ruby和其他一些中,可以为预先存在的祖先类添加一个新方法,并且所有后代都继承它们.我想知道在C#中是否也可以.

例如,我想在Xamarin.Forms中为Page类添加一些方法,这些方法会使它们在所有NavigationPages ContentPages和Page的其他后代上自动可用.你能用C#做那种事吗?

Eni*_*ity 5

是的,通过使用"扩展方法":

void Main()
{
    var foo = new Foo();
    Console.WriteLine(foo.GetDoubleBar());
}

public class Foo
{
    public int Bar => 42;
}

// Defined somewhere else in your code
public static class FooEx
{
    public static int GetDoubleBar(this Foo foo) => foo.Bar * 2;
}
Run Code Online (Sandbox Code Playgroud)

this在关键字static GetDoubleBarstaticFooEx定义的扩展方法.

运行此输出时84.