Using extension methods in .NET 2.0?

前端 未结 1 1057
既然无缘
既然无缘 2020-11-30 03:39

I want to do this, but getting this error:

Error 1 Cannot define a new extension method because the compiler required type \'System.Runtime.Compiler

相关标签:
1条回答
  • 2020-11-30 04:43

    Like so:

    // you need this once (only), and it must be in this namespace
    namespace System.Runtime.CompilerServices
    {
        [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class
             | AttributeTargets.Method)]
        public sealed class ExtensionAttribute : Attribute {}
    }
    // you can have as many of these as you like, in any namespaces
    public static class MyExtensionMethods {
        public static int MeasureDisplayStringWidth (
                this Graphics graphics, string text )
        {
               /* ... */
        }
    }
    

    Alternatively; just add a reference to LINQBridge.

    0 讨论(0)
提交回复
热议问题