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

时间:2009-10-05 21:54:11

标签: c# .net 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 )
    {

    }
}

1 个答案:

答案 0 :(得分: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 )
    {
           /* ... */
    }
}

可替换地;只需添加对LINQBridge的引用。