Domanda

I'm trying to write a generic method that will return specific markup when passed an enum. Below is the method which has been reduced to the minimum required code for this question.

    public static string GetMarkup(Type enumType)
    {
        StringBuilder builder = new StringBuilder();
        foreach (var val in Enum.GetValues(enumType))
        {
            builder.Append(val.ToString());
        }
        return builder.ToString();
    }

The method is called like this where CopyType is an enum:

    GetDropDownListHtml(typeof(CopyType))

The goal is to be able to call ToString() extension methods I've written for the enums I'll pass into this method. The problem is that to make the method generic, I need to use var to declare my variable in the foreach declaration, but that boxes it. Instead of an enum of CopyType, I have an object that is the boxed CopyType.

In response, I've tried many thinks like this, but to no avail:

    ((typeof(enumType))val.ToString()

Any ideas?

È stato utile?

Soluzione

There's no way to use extension methods to do this to a specific enum. You either need to extend your extension method to support all Enum types, add an is statement in there which you can use to only cast it when necessary, or write a special overload to this function which you call just for this type of enum. This has to do with how extension methods are actually implemented.

The compiler turns an extension method into its static form: myCopyType.ToString() becomes CopyType.ToString(myCopyType) when compiled. But with your scenario (or even with generics) the compiler can't tell what type to use, because the type isn't determined until runtime.

This leaves the three choices above.

In my own code, I went with the first option, based on the code here. You'll be able to call .GetLabel() on any Enum type, and you can put your special labels on this one specifically.

Additionally, you'll need to use foreach (Enum val in ... instead, so as to make sure the compiler knows it's an Enum.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top