我有以下用于检查数据库值fe的函数:
public static class ConnectionConst
{
public const int NotConnected = 0;
public const int Connected = 1;
public const int Unknown = 2;
// ...
}
Run Code Online (Sandbox Code Playgroud)
现在我不想在datagrid中显示整数值,而是显示const属性的值.Fe'已连接'而不是'1'.
为什么不使用枚举:
public enum ConnectionConst
{
NotConnected = 0,
Connected = 1,
Unknown = 2
}
Run Code Online (Sandbox Code Playgroud)
您可以拥有此类型的变量:
ConnectionConst connectionState = ConnectionConst.Unknown;
Run Code Online (Sandbox Code Playgroud)
并且在DataGridView值中"Unknown"应该出现
编辑:
如果您已经在使用C#6或更高版本,则还可以在示例中将nameof与静态类一起使用:
string value = nameof(ConnectionConst.Unknown);
Run Code Online (Sandbox Code Playgroud)
如果您想显示带有空格的名称Not Connected而不是NotConnected您可以尝试使用此:
public enum ConnectionConst
{
[Description("Not Connected")]
NotConnected = 0,
[Description("Connected")]
Connected = 1,
[Description("Unknown")]
Unknown = 2
}
public static string DisplayEnumName(Enum value)
{
var name = value.GetType().GetField(value.ToString());
var attributes = (DescriptionAttribute[])name.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes != null && attributes.Length > 0) {
return attributes(0).Description;
} else {
return value.ToString();
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用这个:
var name = DisplayEnumName(ConnectionConst.NotConnected);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
707 次 |
| 最近记录: |