在.NET 2.0中使用扩展方法?

Joa*_*nge 32 .net c# extension-methods

我想这样做,但得到这个错误:

错误1无法定义新的扩展方法,因为无法找到编译器所需的类型"System.Runtime.CompilerServices.ExtensionAttribute".您是否缺少对System.Core.dll的引用?[剪了一些路径]

我在这里看到一些答案说,你必须自己定义这个属性.

我怎么做?

编辑:这就是我所拥有的:

[AttributeUsage ( AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method )]
public sealed class ExtensionAttribute : Attribute
{
    public static int MeasureDisplayStringWidth ( this Graphics graphics, string text )
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 59

像这样:

// 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 )
    {
           /* ... */
    }
}
Run Code Online (Sandbox Code Playgroud)

另外; 只需添加对LINQBridge的引用.

  • 您需要继承Attribute才能将其作为属性...并且需要将其称为ExtensionAttribute,以便编译器可以找到它.(这就是它期望它被调用的.)你的错误可能是它不在静态类中. (3认同)
  • 对于库,将"ExtensionAttribute"声明为内部而不是公共是否有任何危害?(即`内部密封类ExtensionAttribute:Attribute {}`).如果应用程序使用两个同时实现此技巧的库,那么这是更好的做法吗? (2认同)