简体   繁体   中英

Creating an extension method in a .Net 2.0 project, compiling with C# 4.0

I have an old product that I need to update, written in C# and .Net 2.0. The project has been updated to work with Visual Studio 2010 (which includes the C# 4.0 compiler) but I can not upgrade the framework from 2.0 to any higher version.

I've found multiple articles (like this question ) that were written around the time of VS 2008, which shipped with the C# 3.0 compiler, stating that you can create your own extension methods by defining your own extension method attribute class for projects that were written with the 2.0 framework. However, I can not seem to find any reference stating if this is still necessary using C# 4.0 on a .Net 2.0 project.

With my project, will I still need to define the custom extension attribute class or has the C# 4.0 compiler been improved so that it can simplify the process?

I can not seem to find any reference stating if this is still necessary using C# 4.0 on a .Net 2.0 project.

Yes, it is. The compiler needs that attribute. Whether you define it yourself or use the one in System.Core is up to you. Though in your particular case System.Core is not an option since that is only a part of .NET 3.5.

Once you upgrade to a later version, 3.5 or later, you can safely remove this attribute from your project all together and just use the one in System.Core .

If you have upgraded to Visual Studio 2010; then you are using the C# 4.0 compiler. That means all you need is an ExtensionAttribute :

namespace System.Runtime.CompilerServices
{
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
    public class ExtensionAttribute : Attribute
    {
    }
}

It must be in this exact namespace.

Once you've got that somewhere, you can declare an extension method the normal way (since you are using the C# 4.0 compiler):

public static class Extensions
{
    public static string ToTitleCase(this string str)
    {
        //omitted
    }
}

And then use it like an extension method:

var str = "hello world";
str.ToTitleCase();

You yourself don't actually ever need to put the ExtensionAttribute on anything; the C# 4.0 compiler does it for you. Essentially, all the compiler needs is to be able to find an attribute named ExtensionAttribute .

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