当您分配相似的值时,结果会出乎意料,但我认为它会评估两种情况:
当 n 为偶数时:
(n/2)
当 n 为奇数时:
(n/2)+1
如果我像这样更改enum:
enum Weekdays {Mon=1,Tue=1,Wen=1,Thi=1,Fri=1,Sat=1, Sun=1, Mon2=1, Mon3=1}
// n is odd = 9
// (n/2)+1 = 5
Weekdays obj = (Weekdays)1;
Console.WriteLine(obj);
结果将是Fri,现在让我们再次更改enum:
enum Weekdays {Mon=1,Tue=1,Wen=1,Thi=1,Fri=1,Sat=1, Sun=1,Mon2=1}
// n is even = 8
// (n/2) = 4
Weekdays obj = (Weekdays)1;
Console.WriteLine(obj);
结果现在是Thi,再次更改enum:
enum Weekdays {Mon=1,Tue=1,Wen=1,Thi=1,Fri=1,Sat=1, Sun=1}
// n is odd = 7
// (n/2)+1 = 4
Weekdays obj = (Weekdays)1;
Console.WriteLine(obj);
结果现在是Thi,再次更改enum:
enum Weekdays {Mon=1,Tue=1,Wen=1,Thi=1,Fri=1,Sat=1}
// n is even = 6
// (n/2) = 3
Weekdays obj = (Weekdays)1;
Console.WriteLine(obj);
结果现在是Wen,再次更改enum:
enum Weekdays {Mon=1,Tue=1,Wen=1,Thi=1,Fri=1}
// n is odd = 5
// (n/2)+1 = 3
Weekdays obj = (Weekdays)1;
Console.WriteLine(obj);
结果现在是Wen,再次更改enum:
enum Weekdays {Mon=1,Tue=1,Wen=1,Thi=1}
// n is even = 4
// (n/2) = 2
Weekdays obj = (Weekdays)1;
Console.WriteLine(obj);
结果现在是Tue,再次更改enum:
enum Weekdays {Mon=1,Tue=1,Wen=1}
// n is odd = 3
// (n/2)+1 = 2
Weekdays obj = (Weekdays)1;
Console.WriteLine(obj);
结果现在是Tue。
尽管这完美地解释了这种行为,但这可能并不总是发生或可能不会发生,因为我没有检查更多情况,但正如 MSDN 所说,当 enum 具有相同的值时,您不应该假设这样的输出不同的名字...
也就是说,我认为您现在可以轻松理解代码中发生了什么。
参考:Link
编辑:
@GrantWinney 的回答让我想到了这一点,他写道,Array.BinarySearch 传递了值数组和要搜索的值,所以我从名称 Array.BinarySearch 意识到它肯定使用了 BinarySearch 并且解释一切......
Binary Search 将像这样划分数组:
Mid = {Low(which is the starting index) + High (which is the last index of array)}/2
然后检查
if (Mid == value) return index;
else
if the value is smaller or equal move left other wise move right of the array
所以这解释了如果 enum 值是您尝试打印的值的多个名称,它们是如何打印的。
您的原始问题
enum Weekdays
{
Mon = 1,
Tue = 1,
Wen = 1,
Thi,
Fri,
Sat,
Sun
}
Weekdays obj = (Weekdays)1;
Console.WriteLine(obj);//Prints Tue why?
它打印Tue,因为将通过数组调用Array.BinarySearch
{1, 1, 1, 2, 3, 4, 5}
以及要搜索的值 1...
所以BinarySearch 会这样做:
Mid = {Low(0) + High(6)} / 2
if (Mid == value) return index
else move left
再次向左移动后,Mid 将被计算出来:
High = Mid - 1; // now only the left sub-array will be searched
Mid = {Low(0) + High(2)} / 2
if (Mid == value) return index // here the condition will be true and you will be returned with `Tue`
您的问题中的第二个示例:
enum Weekdays
{
Mon = 1,
Tue = 1,
Wen = 1,
Thi = 1,
Fri,
Sat,
Sun
}
Weekdays obj = (Weekdays)1;
Console.WriteLine(obj);//Prints Thi !!!!!How?
正如我在上面写的那样,将调用Array.BinarySearch 和数组:
{1, 1, 1, 1, 2, 3, 4}
将通过 value = 1 传递给搜索...
在数组上应用BinarySearch 算法,它将评估为Thi。