2009-10-05 15 views
31

voglio fare questo, ma sempre questo errore:Utilizzo dei metodi di estensione in .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]

Ho visto alcune risposte qui che dice, si deve definire questo attributo da soli.

Come faccio?

EDIT: Questo è quello che ho:

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

    } 
} 
+1

No; hai bisogno di * due * lezioni; uno per l'attributo; uno per il/i metodo/i di estensione; aggiornerà. –

risposta

58

Come così:

// 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) 
    { 
      /* ... */ 
    } 
} 

alternativa; basta aggiungere un riferimento a LINQBridge.

+0

Grazie Marc, in realtà era il tuo post che ho letto. Ho appena provato, ma ho questo: Errore I metodi di estensione devono essere definiti in una classe statica non generica, dove ho un metodo come questo: public static int MeasureDisplayStringWidth (questa grafica grafica, ...) –

+0

Anche ExtensionAttribute può essere un nome qualsiasi, giusto? E perché ereditare dall'attributo? –

+3

È necessario ereditare da Attributo perché sia ​​un attributo ... e deve essere chiamato ExtensionAttribute in modo che il compilatore possa trovarlo. (Questo è quello che si aspetta che venga chiamato.) Il tuo errore è probabilmente che non è in una classe statica. –

Problemi correlati