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
1.1k views
in Technique[技术] by (71.8m points)

c# - Using an enum having entries with the same value of underlying type

if i declare an enum like

enum Weekdays
{
    Mon = 1,
    Tue = 1,
    Wen = 1,
    Thi,
    Fri,
    Sat,
    Sun
}

Weekdays obj = (Weekdays)1;
Console.WriteLine(obj);//Prints Tue why?

now if i change Weekdays and do the same operation as follows

enum Weekdays
{
    Mon = 1,
    Tue = 1,
    Wen = 1,
    Thi = 1,
    Fri,
    Sat,
    Sun
}

Weekdays obj = (Weekdays)1;
Console.WriteLine(obj);//Prints Thi !!!!!How?

What is really happening here?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

When you write out your value like this, it ends up getting ToString() called on it.

Console.WriteLine(obj);

If you dig into the code far enough down, it's calling Enum.GetName() on your value.

Regarding multiple enum values with the same underlying value, the Enum.GetName page on MSDN says:

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.

It doesn't state how it determines which name to return if the values on two or more are the same.

The docs for Enum.ToString() include the same warning, in slightly different wording.

Digging a little deeper, the method above makes a call to Array.BinarySearch, passing it an array of numbers representing all values in your enum, and a number representing the value you want to print.

So you have an array with multiple 1's in it, and you're searching for a 1. The docs for that call are similar:

Duplicate elements are allowed. If the Array contains more than one element equal to value, the method returns the index of only one of the occurrences, and not necessarily the first one.

Again, it doesn't state how a selection is made, just that it'll be unreliable.


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

...