dav*_*459 1 .net c# extension-methods
在之前的组织中,我们实现了一个扩展方法,该方法为String.Format创建了一个简写.该方法称为"String.F".但是我似乎无法让这个工作.一位前同事给了我以下代码,我将在下面列出我自己的测试方法.在函数'Test()'中,"String.F"抛出并出错,并且不会在intellisence中显示.我会问这是不可能的,但是我已经使用对此方法的调用来编写代码.这只是在使用实例化字符串时才有可能吗?谢谢.
public static class MyExtensions {
public static string F(this string target, params object[] args) {
return "hello";
}
}
class TestExtensions {
public string Test() {
return String.F("test:{0}", "test");
}
}
Run Code Online (Sandbox Code Playgroud)
您不能执行扩展方法并在静态上下文中使用它.扩展方法只能用作实例方法.
你可以做
public static string F(this string target, params object[] args) {
return String.Format(target, args);
}
Run Code Online (Sandbox Code Playgroud)
并像这样使用它
"test:{0}".F("test");
Run Code Online (Sandbox Code Playgroud)