我想创建一个适用于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)
您需要定义扩展方法:
public static class StringExtensions {
public static string MyNewMethod(this string s) {
// do something and return a string
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,扩展方法是static在static顶级类中定义的.
| 归档时间: |
|
| 查看次数: |
53 次 |
| 最近记录: |