创建适用于String对象的方法

Oti*_*iel 2 c# inheritance

我想创建一个适用于String对象的方法,它将返回一个修改过的String:

String s = "blabla";
String result = s.MyNewMethod();
Run Code Online (Sandbox Code Playgroud)

我试图创建一个新类,String但关键字this似乎未知:

class String  {

    public String MyNewMethod() {
        String s = this.Replace(',', '.'); // Replace method is unknown here
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

jas*_*son 8

您需要定义扩展方法:

public static class StringExtensions {
    public static string MyNewMethod(this string s) {
        // do something and return a string
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,扩展方法是staticstatic顶级类中定义的.