Bry*_*ant 2 c# extension-methods
我知道这是一个愚蠢的错误,但我无法弄清楚发生了什么.我已经创建了一些扩展方法,并尝试访问它们,但默认方法不断被调用:
namespace MyProject
{
public static class Cleanup
{
public static string cleanAbbreviations(this String str) {
if (str.Contains("JR"))
str = str.Replace("JR", "Junior");
return str;
}
public static bool Contains(this String str, string toCheck)
{//Ignore the case of our comparison
return str.IndexOf(toCheck, StringComparison.OrdinalIgnoreCase) >= 0;
}
public static string Replace(this String str, string oldStr, string newStr)
{//Ignore the case of what we are replacing
return Regex.Replace(str, oldStr, newStr, RegexOptions.IgnoreCase);
}
}
}
Run Code Online (Sandbox Code Playgroud)
仅当找不到合适的实例方法时,编译器才会查找扩展方法.您不能以这种方式隐藏现有的实例方法.
例如,已经有Contains声明的方法string,其中一个string作为参数.这就是为什么不调用你的扩展方法的原因.
来自C#规范:
7.6.5.2扩展方法调用
前面的规则意味着实例方法优先于扩展方法,内部命名空间声明中可用的扩展方法优先于外部命名空间声明中可用的扩展方法,并且直接在命名空间中声明的扩展方法优先于导入到该命名空间中的扩展方法.带有using namespace指令的命名空间.
| 归档时间: |
|
| 查看次数: |
174 次 |
| 最近记录: |