gpt4 book ai didi

c# - Enum.GetValues() 是否使用反射?

转载 作者:行者123 更新时间:2023-11-30 12:55:08 27 4
gpt4 key购买 nike

Enum.GetValues() 是否使用反射?

我认为不会,因为在编译时它应该能够获取可能值的列表并存储它们。但我不知道它是否确实如此。

最佳答案

我觉得应该。下面是完成这项工作的代码

    // This will return enumValues and enumNames sorted by the values.
private void GetEnumData(out string[] enumNames, out Array enumValues)
{
Contract.Ensures(Contract.ValueAtReturn<String[]>(out enumNames) != null);
Contract.Ensures(Contract.ValueAtReturn<Array>(out enumValues) != null);

FieldInfo[] flds = GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);

object[] values = new object[flds.Length];
string[] names = new string[flds.Length];

for (int i = 0; i < flds.Length; i++)
{
names[i] = flds[i].Name;
values[i] = flds[i].GetRawConstantValue();
}

// Insertion Sort these values in ascending order.
// We use this O(n^2) algorithm, but it turns out that most of the time the elements are already in sorted order and
// the common case performance will be faster than quick sorting this.
IComparer comparer = Comparer.Default;
for (int i = 1; i < values.Length; i++)
{
int j = i;
string tempStr = names[i];
object val = values[i];
bool exchanged = false;

// Since the elements are sorted we only need to do one comparision, we keep the check for j inside the loop.
while (comparer.Compare(values[j - 1], val) > 0)
{
names[j] = names[j - 1];
values[j] = values[j - 1];
j--;
exchanged = true;
if (j == 0)
break;
}

if (exchanged)
{
names[j] = tempStr;
values[j] = val;
}
}

enumNames = names;
enumValues = values;
}

注意 FieldInfo[] flds = GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); 行。看起来真的很像反射法。GetFields 方法是抽象的

 abstract public FieldInfo[] GetFields(BindingFlags bindingAttr);

所以我不确定枚举是如何实现的。

关于c# - Enum.GetValues() 是否使用反射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51560377/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com