2009-10-05 96 views
31

我想這樣做,但得到這個錯誤:在.NET 2.0中使用擴展方法?

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? [snipped some path stuff]

我這裏,說看到了一些答案,你必須定義此屬性自己。

我該怎麼做?

編輯:這是我有:

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

    } 
} 
+1

否;你需要*兩個*類;一個用於屬性;一個用於擴展方法;將更新。 – 2009-10-06 05:06:21

回答

58

像這樣:

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

+0

謝謝馬克,它實際上是我閱讀的帖子。我只是試過,但得到了:錯誤擴展方法必須在非泛型靜態類中定義,其中我有一個像這樣的方法: public static int MeasureDisplayStringWidth(this Graphics graphics,...) – 2009-10-05 21:58:48

+0

另外ExtensionAttribute可以是任何名字,對吧?爲什麼繼承自Attribute? – 2009-10-05 21:59:32

+3

您需要從屬性繼承它作爲屬性...並且它需要被稱爲ExtensionAttribute,以便編譯器可以找到它。 (這就是它期望它被調用的方式。)你的錯誤可能是它不在靜態類中。 – 2009-10-05 22:03:04