2009-10-05 5 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

아니요; 당신은 * 두 클래스가 필요합니다; 속성에 대해 하나; 하나의 확장 방법 (들); 업데이트됩니다. –

답변

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 (이 그래픽 그래픽, ...) –

+0

또한 ExtensionAttribute 수 있습니다. 이름이 뭐든, 그렇지? 왜 Attribute를 상속합니까? –

+3

속성으로 속성을 상속하려면 속성에서 상속해야하며 컴파일러가 찾을 수 있도록 ExtensionAttribute라고 호출해야합니다. (그것이 그것이 호출되기를 기대하는 것입니다.) 여러분의 에러는 아마 그것이 정적 클래스가 아니라는 것입니다. –