在ruby和其他一些中,可以为预先存在的祖先类添加一个新方法,并且所有后代都继承它们.我想知道在C#中是否也可以.
例如,我想在Xamarin.Forms中为Page类添加一些方法,这些方法会使它们在所有NavigationPages ContentPages和Page的其他后代上自动可用.你能用C#做那种事吗?
是的,通过使用"扩展方法":
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
GetDoubleBar
的static
类FooEx
定义的扩展方法.
运行此输出时84
.
归档时间: |
|
查看次数: |
60 次 |
最近记录: |