开发者

Extension Method in .net 2.0 in VS2008

  public static class开发者_运维技巧 Helper
  {
    public static float ToFloat(this string input)
    {
      float result;
      return float.TryParse(input, out result) ? result : 0;
    }
  }

I have added the following at top:

namespace System.Runtime.CompilerServices
{
    [AttributeUsage(AttributeTargets.Method)]
    public class ExtensionAttribute : Attribute
    {
        public ExtensionAttribute()
        {

        }
    }
}

But still I get Type expected error on "this" in Helper class. What's the problem ?


Weird, the following compiles and runs fine when targeting .NET 2.0:

using System;

namespace System.Runtime.CompilerServices
{
    [AttributeUsage(AttributeTargets.Method)]
    public class ExtensionAttribute : Attribute
    {
        public ExtensionAttribute()
        {

        }
    }
}

public static class Helper
{
    public static float ToFloat(this string input)
    {
        float result;
        return float.TryParse(input, out result) ? result : 0;
    }
}

class Program
{
    static void Main()
    {
        string foo = "123";
        Console.WriteLine(foo.ToFloat());
    }
}


EDIT:

The reason that it does work in a command line application is because msbuild knows that the 2.0 .NET CLR can handle extension methods (as they are just static methods with some syntactic sugar).

When compiling a project, msbuild checks the .csproj file for how to compile, what to target etc.

But when compiling a website, there is no .csproj file so msbuild cannot check how to compile. What happens now is that csc, the command line compiler, is launched with parameters of how to compile. So when compiling a .Net 2.0 website, it chooses the 2.0 compiler. But the 2.0 compiler does not know anything about how to compile the extension methods, thus the errors.

You can also notice that if you set the build options under advanced for a regular project to use ISO-2, it will warn you that you cannot use extension methods. But the 2.0 compiler doesn't even recognize the extension methods so it just tells you that you cannot use this

Original post:

I think there is something else wrong in your code, this compiles just fine in .net 2.0:

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string test = "0.0";
            float f = test.ToFloat();
        }

    }
    public static class Helper
    {
        public static float ToFloat(this string input)
        {
            float result;
            return float.TryParse(input, out result) ? result : 0;
        }
    }
}
namespace System.Runtime.CompilerServices
{
    [AttributeUsage(AttributeTargets.Method)]
    public class ExtensionAttribute : Attribute
    {
        public ExtensionAttribute()
        {

        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜