【问题标题】:Using extension methods in .NET 2.0?在 .NET 2.0 中使用扩展方法?
【发布时间】:2009-10-05 21:54:11
【问题描述】:

我想这样做,但收到此错误:

错误 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 )
    {

    }
}

【问题讨论】:

  • 否;你需要两个类;一个用于属性;一种用于扩展方法;会更新。

标签: c# .net extension-methods


【解决方案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 的引用即可。

【讨论】:

  • 谢谢 Marc,我读到的是你的帖子。我刚试过但得到了这个:错误1扩展方法必须在非泛型静态类中定义,我有一个这样的方法:public static int MeasureDisplayStringWidth (this Graphics graphics, ...)
  • ExtensionAttribute 也可以是任何名称,对吧?为什么要从 Attribute 继承?
  • 您需要从 Attribute 继承才能使其成为属性...并且需要将其称为 ExtensionAttribute 以便编译器可以找到它。 (这就是它所期望的调用方式。)您的错误可能是它不在静态类中。
  • 谢谢乔恩,我明白你的意思了。现在这是我不明白的。我的扩展类方法去哪儿了?该类是否使用我的方法进入此 ExtensionAttribute 内部?
  • 对于图书馆,将ExtensionAttribute 声明为内部而不是公共有什么害处吗? (即internal sealed class ExtensionAttribute : Attribute { })。如果应用程序使用两个都实现了这个技巧的库,这会是更好的做法,以避免冲突吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-24
  • 2012-07-05
  • 1970-01-01
  • 2018-12-14
  • 2012-06-17
  • 1970-01-01
相关资源
最近更新 更多