开发者

Extension methods + Console apps

Ok, i'm well and truly stumped here.

I've written extension methods before, and never had any problems. However, i've never had to use them in Console Apps. The following code won't compile and I have no idea why! I created a simple console app to try it out and开发者_如何学Python it just won't work:

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = "hello";

            Console.WriteLine(s.TestMethod());

            Console.Read();
        }
    }

    public static class ExtensionTest
    {
        public static string TestMethod(this string input)
        {
            return input.ToUpper();
        }
    }
}

Can anyone see what's wrong here?

The first error i'm running into is "Type expected" on line 21, which is:

(this string input)

I know i could quite easily just change to:

Console.WriteLine(ExtensionTest.TestMethod(s));

But i'd really like to know why i can't write this extension method in a console app.

Thanks for any help!


Just created a new Console application using that exact text and it compiled and worked as expected. Sure it's targeting the right framework?


You sure you are using C#3.0? The code doesn't have a problem in it.

If you are targeting .NET 2.0 with C# 3.0 you can still ue extension methods by defining the following type in your project:

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


It seems, your project is set up to compile for v2.0 of .NET framework. Try switching to v3.5 in project properties and referencing System.Core assembly..


Ensure your project targets .NET Framework v3.0 or higher and make sure System.Core is a referenced assembly in your project.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜