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

32

我想做这件事,但是出现了这个错误:

Error 1 Cannot define a new extension method because the compiler required type 'System.Runtime.CompilerServices.ExtensionAttribute' cannot be found. Are you missing a reference to 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
不,你需要两个类;一个用于属性,一个用于扩展方法;将会更新。 - Marc Gravell
1个回答

61

就像这样:

// 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的引用。


3
要将一个类定义为属性,需要从Attribute继承。同时,类名必须命名为"ExtensionAttribute",这样编译器才能找到它(编译器期望类名为ExtensionAttribute)。你的错误可能是因为该类不在静态类中。 - Jon Skeet
1
谢谢Jon,我明白你的意思了。现在我不明白的是,我的扩展类方法应该放在哪里?我的类是否应该与我的方法一起放在这个ExtensionAttribute中? - Joan Venge
2
对于库来说,将 ExtensionAttribute 声明为 internal 而不是 public 会有什么危害吗?(即 internal sealed class ExtensionAttribute : Attribute { })。如果一个应用程序使用了两个都实现了这个技巧的库,这样做是否更好,以避免冲突? - rkagerer
很遗憾,这并不能解决“在多个程序集中定义”的警告问题(当在>= 3.5的程序中使用该库时)。我现在只是编译一个针对3.5的单独库。 - Bob
如果您正在使用 .Net 2.0 版本,那么也可能会出现此错误。当我切换到版本3.5时,问题得到了解决,尽管我没有添加属性和密封类类型。 - Zain Ul Abidin
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接