简体   繁体   中英

Using extension methods in .NET 2.0?

I want to do this, but getting this error:

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]

I have seen some answers here that says, you have to define this attribute yourself.

How do I do that?

EDIT : This is what I have:

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

    }
}

Like so:

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

Alternatively; just add a reference to LINQBridge .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM