Вопрос

We have a big Enum class for EDI Fields, just to make a short example, the enums are declared like:

[Description("Ebene")]
Ebene,

[Description("Zaehlpunktdaten")]
Zaehlpunktdaten,

[Description("Zaehlpunkt")]
Zaehlpunkt,

. .

Well, the enums works fine when you retrieve them by EDIEnums.Zaehlpunktdaten.ToString(), but in some other projects, it returns a wrong value.

If I add a new one in the beginning will return exactly the next one, in this example, if I just had added Ebene and I want to retrieve Zaehlpunktdaten, it will return me Zaehlpunkt.

We have tried also with =0, =1, =2 etc, and it doesn't work neither. Also with local references.

Any ideas about what is happening?

Это было полезно?

Решение

Let's say assembly A defines MyEnum. By default, each enum value is implicitly assigned an integer "index", something like this:

public enum MyEnum
{
    X = 1,
    Y = 2,
    Z = 3
}

If the source code in assembly B makes use of MyEnum.Y, that code will be compiled against the value at index 2.

If you now add a new item at the beginning, the indexes will shift:

public enum MyEnum
{
    New = 1,
    X = 2,
    Y = 3,
    Z = 4
}

Assembly B is still refering to the value at index 2, which is now X instead of Y. This is the error you're seeing. This is why adding new enum values is considered a breaking change.

If you expected the enumeration to change, you should have numbered the enum values yourself, instead of using implicit numbering, before compiling assembly B.

You now have two options:

  1. A possible workaround is to add the new value at the end of the enumeration, to avoid shifting the indexes. But this is a sloppy workaround.
  2. Consider numbering the enum values now and rebuild any projects depending on that assembly. It might look like a lot of work, depending on how many projects depend on assembly A, but it'll save you and your co-workers from running into this same issue again in the future.
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top