Perhaps a stupid question. Is it possible to convert one enum to another? For example
Namespace1.Enum1 a = Namespace1.Enum1.Value1.
Namespace2.Enum1 b = (Namespace2.Enum1) a.
If so, under what conditions, please describe

  • one
    Bring both Enum - Andrew NOP
  • one
    the previous comment is correct, since enum is essentially a number, simply if they have the same numerical values, it is enough to explicitly bring one to the other, if they are different, but there is a definite pattern, then we bring to the numerical value and add (decrease, multiply) - Alexsandr Ter

1 answer 1

Can. Suppose you have two listings.

enum Enum1 { AA, BB, CC } enum Enum2 { AA, BB } 

To convert, you first need to get the name of the element of the first enum and use Enum.Parse () to convert it to the second.

 // Предположим это элемент первого Enum1 Enum1 first = Enum1.AA; // Получаем его имя в строковом формате string firstName = first.ToString(); // try нужен в случае, если во втором перечислении отсутствует элемент из первого (например Enum1.CC) try { // Преобразуем во второй Enum2 Enum2 second = (Enum2)Enum.Parse(typeof(Enum2), firstName); } catch { } 

Or you can parse using TryParse.

 if (Enum.TryParse(firstName, out Enum2 result)) { // Тут код в случае, если получилось преобразовать // Результатом является result } 
  • Well, for some simple cases, this is suitable, yes. But I agree with @Alexsandr Ter: you may need a formula to bring some ints to others (multiplication, subtraction). And maybe the conversion is tricky enough to have to write a conversion table. But that's a plus, yes. - AK