Strongly Typed Enum Method Parameter

Consider the following code

enum HorizontalAlignment { Left, Middle, Right };
enum VerticleAlignment { Top, Middle, Bottom };

function OutputEnumValues (Type enumType)
{
    foreach (string name in Enum.GetNames(typeof(enumType)))
    {
        Console.WriteLine(name);
    }
}

Which can be called as

OutputEnumValues (typeof(HorizontalAlignment));
OutputEnumValues (typeof(VerticleAlignment ));

But I could inadvertently call, for example

OutputEnumValues (typeof(int));

And this will compile, but the runtime crashes in Enum.GetNames ()

Any way to write a method signature to catch this problem at compile time - that is, only accept enumeration types in OutputEnumValues?

+3
source share
4 answers

Each type of enumeration is simply an integer (which can be 8-, 16-, 32- or 64-bit and signed or unsigned). You can specify an integer 0for any type of enumeration, and it will become a value that is statically entered into the enumeration.

, Enum, , , .

, :

public static void OutputEnumValues(Enum example)
{
    foreach (string name in Enum.GetNames(example.GetType()))
    {
        Console.WriteLine(name);
    }
}

:

OutputEnumValues((HorizontalAlignment) 0);
OutputEnumValues((VerticalAlignment) 0);

.

+4

, #.

Enum, , , , .

, , , :

public static void OutputValues<T>() where T : struct
{
    if (!typeof(T).IsEnum)
        throw new NotSupportedException("Argument must be an enum.");

    // code here...
}

, , , , Enum.

+1

, , Enum. #.

Jon Skeet : - ?

, ,

public void OutputEnumValues<T>() where T : HorizontalAlignment
{
    foreach (string name in Enum.GetNames(typeof(T)))
    {
        Console.WriteLine(name);
    }
}

, Jon.

+1

"", .

, Type. . , , . . , , , .

, . , , , . API , .

0

Source: https://habr.com/ru/post/1766568/


All Articles