使用.NET 2.0中的扩展方法?(Using extension methods in .NET

2019-07-21 01:09发布

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

因为编译器所需的类型“System.Runtime.CompilerServices.ExtensionAttribute”无法找到网页错误1无法定义新的扩展方法。 你缺少System.Core.dll参考? [剪断一些路径的东西]

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

我怎么做?

编辑 :这是我有:

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

    }
}

Answer 1:

像这样:

// 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 。



文章来源: Using extension methods in .NET 2.0?