Identify enumerations with the same base value correctly

Suppose I defined this enumone where several members have the same basic value:

enum Number
{
  One = 1,
  Eins = 1,
  Uno = 1
}

According to the MSDN documentation :

If several enumeration elements have the same base value, and you are trying to get a string representation of the name of an enumeration member based on its base value, your code should not make any assumptions about which name the method returns.

So for example

var number = Number.One;
Console.WriteLine(number);

gives me the following result:

Eins

Print all enumeration items,

Console.WriteLine($"{Number.One} {Number.Eins} {Number.Uno}");

outputs the following result:

Eins eins eins

However, taking nameofeach member,

Console.WriteLine($"{nameof(Number.One)} {nameof(Number.Eins)} {nameof(Number.Uno)}");

gives the following result:

One Eins Uno

, , enum . , .. - Number , , ?

+6
3

, , enum

, ... .

, nameof , . . , nameof a const:

const string a = nameof(Number.One);

.

, , , :

const string a = $"{Number.One}";

, :

- Number , , ?

- "".

+7

, , , - enum , , ( , ). , / .

SomeMethod

Console.WriteLine("{0:G}", (KnownNumber)Number.Eins); // > One
Console.WriteLine("{0:G}", (KnownNumber)Number.Uno); // > One
Console.WriteLine("{0:G}", (KnownNumber)Number.One); // > One

Enums.cs

public enum Number
{
  One = 1,
  Eins = 1,
  Uno = 1
}

public enum KnownNumber
{
  One = 1,
  Two = 2,
  Three = 3
}

Fiddle

+1

I wrote something that should make it work

public static class NumberExtension
{
    private static Dictionary<int, string> pointers = new Dictionary<int, string>();
    public static unsafe void SetValue(this Number source, string value)
    {
        if (pointers.ContainsKey((int)&source))
            pointers[(int)&source] = value;
        else
            pointers.Add((int)&source, value);
    }
    public static unsafe string GetValue(this Number source)
    {
        if (pointers.ContainsKey((int)&source))
            return pointers[(int)&source];
        return source.ToString();
    }
}

And use:

    Number num = default(Number);
    num.SetValue(nameof(Number.Uno));
    Console.WriteLine(num.GetValue());

However, it looks like a hack, and I DO NOT recommend it. It would be better if you were looking for the best solution.

0
source

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


All Articles