未看到C#扩展方法
我知道这是一个愚蠢的错误,但我不知道发生了什么。我已经创建了一些扩展方法并试图访问它们,但默认方法不断被调用:未看到C#扩展方法,c#,extension-methods,C#,Extension Methods,我知道这是一个愚蠢的错误,但我不知道发生了什么。我已经创建了一些扩展方法并试图访问它们,但默认方法不断被调用: namespace MyProject { public static class Cleanup { public static string cleanAbbreviations(this String str) { if (str.Contains("JR")) str = str.Re
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);
}
}
}
编译器仅在找不到合适的实例方法时才查找扩展方法。不能以这种方式隐藏现有实例方法 e、 g.
Contains
方法已在string
上声明,该方法将一个string
作为参数。这就是为什么不调用扩展方法的原因
根据C#规范:
7.6.5.2扩展方法调用
前面的规则意味着实例方法优先于
扩展方法,即内部可用的扩展方法
命名空间声明优先于扩展方法
在外部命名空间声明中可用,并且该扩展方法
直接在命名空间中声明的优先于扩展
方法导入到具有using命名空间的同一命名空间中
指令
编译器总是更喜欢类型的实际实例方法,而不是扩展方法中的匹配重载。如果您想解决这个问题(或者为扩展方法指定不同的名称),则需要在不使用扩展名sugar的情况下调用它们:
请注意,您可以省略
清理。
从清理的其他方法中删除它
-为了清晰起见,我在这里包含它。您是否在希望使用它的位置包含了名称空间?例如使用MyProject代码>因此,在这种情况下,最好的办法就是将我的“扩展”命名为BlindContains()
和BlindReplace()
,或者有更优雅的方法来实现吗?您可以更改名称,或者使用静态方法调用语法调用它们:Cleanup.Contains(source,search)
if(Cleanup.Contains(str, "JR"))
str = Cleanup.Replace(str, "JR", "Junior");