C# Extension methods in .NET 2.0

后端 未结 5 1846
走了就别回头了
走了就别回头了 2021-01-13 16:05

I have found several links to methods of making extension methods work in .NET2.0 (The moth, Discord & Rhyme, Stack Overflow). I have also heard vaguely from a colleague

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-13 16:18

    Personally, I would recommend avoiding all three. Each option makes this work by performing a "trick" - I would not rely on this for production code.

    If you want to use extension methods, upgrade to C# 3.0. Otherwise, just stick to calling the method using the non-extension method syntax.

    You can always take an extension method call like so:

    public static class Utility {
        public static string Extension(this string original) { ... }
    
    // call with:
    var newString = myString.Extension();
    

    And call it directly:

    string newString = Utility.Extension(myString);
    

    This will be more consistent with C#/.NET 2 syntax, and would be my recommendation.

提交回复
热议问题