Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

c# - GetName for enum with duplicate values

If I have duplicate values in a C# enum, saying

enum MyE {
  value1 = 1,
  value2 = 2,
  valued = 1
}

What should be the values of the following strings?

MyE N = (MyE)1;
string V1 = N.ToString();
string V2 = GetName(MyE, 1);

Is it true that V1 and V2 must contain the same values? What these values should be?

I haven't found anything in MSDN or here concerning such a ?dereferencing? of enums with duplicates, point me to a link, please, if I missed that.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Experimentation shows that:

V1 = "value1"

and

V2 = "value1"

However, this isn't guaranteed. The MSDN page on Enum.GetName states:

If multiple enumeration members have the same underlying value, the GetName method guarantees that it will return the name of one of those enumeration members. However, it does not guarantee that it will always return the name of the same enumeration member. As a result, when multiple enumeration members have the same value, your application code should never depend on the method returning a particular member's name.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...