开发者

Extension methods to extend class members?

I'd like to write an extension method that extends some member of my class. Specifically, I'd like to extend an enum. However, this is not working:

namespace mynamespace
{
    public class myclass
    {
        public enum ErrorCodes
        {
            Error1, Error2, Error3
        }

        public static double GetDouble(this ErrorCodes ErrorCode)
        {
            return (double)((int)ErrorCode);
        }

        public void myfunc()
        {
            Error开发者_如何学JAVACodes mycode;
            MessageBox.Show(mycode.GetDouble().ToString());
        }
    }
}

Specifically, it doesn't recognize GetDouble() as an extension. This is not just for enums either, I tried creating an extension method for doubles and had the same problem, too.


You can only write extension methods in top-level, static, non-generic classes, but they can extend nested classes. Here's a complete example, based on your code:

using System;

public static class Extensions
{
    public static double GetDouble(this Outer.ErrorCode code)
    {
        return (double)(int)code;
    }
}

public class Outer
{
    public enum ErrorCode
    {
        Error1, Error2, Error3
    }
}

public class Test
{
    public static void Main()
    {
        Outer.ErrorCode code = Outer.ErrorCode.Error1;
        Console.WriteLine(code.GetDouble());
    }
}


The extension method must be defined in a static class.

See the manual.

edit

As Jon pointed out, the static class must be top-level, not nested.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜