开发者

Extension methods and Enums

I have a Enum

Public Enum MyEnum
    <StringValue("Bla Bla")> _
    BlaBla

    <StringValue("bbble bbble")> _
    BleBle
End Enum

I did an extension method (GetStringValue) that takes an Enum and returns the value of the StringValueAttribute, if any.

I can do Dim sValue = MyEnum.BlaBla.GetStringValue()

Now, I want an "extension" method that returns to me all the Enum Va开发者_开发技巧lues as a list of strings.

I want to apply it like this: MyEnum.GetStringValues()

Is it possible?


While you can't add a static extension method to a type, you could declare a new class as follows:

class EnumHelper
{
    public static IEnumerable<string> GetStringValues<TEnum>()
        where TEnum : struct, IComparable, IFormattable, IConvertible
    {
        var enumType = typeof(TEnum);

        if (!enumType.IsEnum) {
            throw new ArgumentException("T must be an enumerated type");
        }

        foreach (Enum item in Enum.GetValues(enumType))
        {
            yield return item.GetStringValue();
        }
    }
}

and call it as follows:

class Program
{
    enum Rainbow { Red, Orange, Yellow, Green, Blue, Indigo, Violet }

    static void Main(string[] args)
    {
        foreach (var item in EnumHelper.GetStringValues<Rainbow>())
        {
            Console.WriteLine(item);

        }

        Console.ReadKey(false);
    }
}


Is it possible?

No. You can add extension methods to instances of specific types, but not to specific types themselves.

Here's one way to think about this: extension methods are merely syntactic sugar for static methods on static classes where first parameter of the method is the "receiver" of the extension method. Is it possible to write a static method on a static class that has its first parameter something like MyEnum? No. You can't pass type names as parameters to methods (you can passes instances of type handles (e.g., typeof(MyEnum)), but not the type name itself). Thus, what you are asking is not possible.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜