2009-10-05 13 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]

私はあなたがこの属性を自分で定義する必要があり、言うことここにいくつかの答えを見てきました。

どうすればよいですか?

EDIT:これは私が持っているものですので、同様

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

    } 
} 
+1

いいえ。あなたは* 2つのクラスが必要です。属性の1つ。 1つは拡張メソッド用です。更新されます。 –

答えて

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

ありがとうMarc、実際に私が読むあなたの記事でした。私はちょうど試みたが、これを持っていた:エラーエクステンションメソッドは、このようなメソッドを持っている非ジェネリックな静的クラスで定義する必要があります: public static int MeasureDisplayStringWidth(Graphics graphics、...) –

+0

ExtensionAttribute名前はありますか?なぜ属性から継承するのですか? –

+3

属性であるためにはAttributeから継承する必要があります。また、ExtensionAttributeという名前でコンパイラーが検索できるようにする必要があります。 (それはそれが呼び出されることを期待しているものです。)あなたのエラーはおそらくそれが静的クラスにないことです。 –

関連する問題