简体   繁体   English

Enum.GetValues 和 Enum.GetNames 的区别

[英]Difference between Enum.GetValues and Enum.GetNames

I see the Enum.GetValues returns base Array type and Enum.GetNames returns a string array.我看到Enum.GetValues返回基本Array类型,而Enum.GetNames返回一个string数组。 But I don't understand how this is very significant.但我不明白这是多么重要。 For an enum anyways, the values are strings.无论如何,对于enum ,值是字符串。

But, there is an associated problem.但是,有一个相关的问题。 The DataGridView ComboBox column databinds to an enum if I give the DataSource = Enum.GetValues , but it doesn't databind when I give it Enum.GetNames as a DataSource .如果我给DataSource = Enum.GetValues ,则DataGridView ComboBox列数据绑定到enum ,但当我给它Enum.GetNames作为DataSource时它不会数据绑定。

GetValues will return an Array of the underlying integer values for each item in the Enum. GetValues将为 Enum 中的每个项目返回一个包含基础整数值的数组。

GetNames will return a string array of the Names for the items in the enum. GetNames将返回枚举中项目名称的字符串数组。

The Array returned by GetValues implements IList while the string[] returned by GetNames does not, which explains the binding differences. GetValues 返回的 Array 实现了 IList 而 GetNames 返回的 string[] 没有实现,这就解释了绑定差异。

Enums are actually numeric.枚举实际上是数字。 GetNames returns the field names. GetNames返回字段名称。 GetValues returns the numeric values. GetValues返回数值。

MSDN has a great sample on GetValues . MSDN 在GetValues上有一个很好的示例。

Think of enumerations as Name/Value pairs.将枚举视为名称/值对。

enum SignMagnitude { Negative = -1, Zero = 0, Positive = 1 };

In the example above, GetNames() will return a string array containing the items "Negative", "Zero", and "Positive."在上面的示例中, GetNames()将返回一个string数组,其中包含项“Negative”、“Zero”和“Positive”。 GetValues() will return an array of SignMagnitude containing SignMagnitude.Negative , SignMagnitude.Zero and SignMagnitude.One . GetValues()将返回的数组SignMagnitude含有SignMagnitude.NegativeSignMagnitude.ZeroSignMagnitude.One


There is an example of binding Enum names to a dropdown in a DataGridView here: Create drop down list options from enum in a DataGridView这里有一个将枚举名称绑定到 DataGridView 中的下拉列表的示例: 从 DataGridView 中的枚举创建下拉列表选项

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM