简体   繁体   中英

C# Extension Method Not Seen

I know this is a silly mistake, but I can't figure out what's going on. I've created some extension methods and am trying to access them, but the default methods keep getting called:

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);
        }

    }
}

Compiler looks for extension methods only when no suitable instance method is found. You can't hide existing instance methods this way.

eg There already is Contains method declared on string that takes one string as parameter. That's why your extension method isn't called.

From C# specification:

7.6.5.2 Extension method invocations

The preceding rules mean that instance methods take precedence over extension methods , that extension methods available in inner namespace declarations take precedence over extension methods available in outer namespace declarations, and that extension methods declared directly in a namespace take precedence over extension methods imported into that same namespace with a using namespace directive.

The compiler will always prefer a type's actual instance methods over matching overloads in extension methods. You'll need to call them without the extension sugar if you want to get around this (or give the extension methods different names):

if(Cleanup.Contains(str, "JR"))
    str = Cleanup.Replace(str, "JR", "Junior");

Note that you can omit Cleanup. from within other methods of Cleanup - I am including it here for clarity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM