如何使用const int属性的名称

时间:2017-08-04 08:25:20

标签: c# const

我使用以下功能来检查数据库值f.e。:

public static class ConnectionConst
{
    public const int NotConnected = 0;
    public const int Connected = 1;
    public const int Unknown = 2;
    // ...
}

现在我不想在datagrid中显示整数值,而是显示const属性的值。 F.E. '连接'而不是' 1'。

3 个答案:

答案 0 :(得分:8)

为什么不使用枚举:

public enum ConnectionConst
{
    NotConnected = 0,
    Connected = 1,
    Unknown = 2
}

您可以拥有此类型的变量:

ConnectionConst connectionState = ConnectionConst.Unknown;

并在DataGridView中显示值"Unknown"

编辑:

如果您已经在使用C#6或更高版本,那么您也可以在示例中使用nameof和静态类:

string value = nameof(ConnectionConst.Unknown);

答案 1 :(得分:6)

如果您希望使用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();
    }
}

然后就这样使用:

var name = DisplayEnumName(ConnectionConst.NotConnected);

答案 2 :(得分:0)

除了XardasLord和DavidG建议的内容之外,我还要将该枚举说明放入IValueConverter

public class EnumDescriptionConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
            return "";

        string stringRepresentation = value.ToString();
        Type T = value.GetType();
        if (!T.IsEnum) return stringRepresentation;

        MemberInfo[] enumMembers = T.GetMember(stringRepresentation);
        if (enumMembers.Length <= 0) return stringRepresentation;

        DescriptionAttribute[] memberAttributes = enumMembers[0].GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];
        if (memberAttributes == null) return stringRepresentation;
        if (memberAttributes.Length <= 0) return stringRepresentation;

        return memberAttributes[0].Description;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        // Or Binding.DoNothing, or throw an Exception, whichever you prefer
        return DependencyProperty.UnsetValue;
    }
}

并在列的绑定中使用它:

<DataGrid>
    <DataGrid.Resources>
        <local:EnumDescriptionConverter x:Key="DescriptionConverter"/>
    </DataGrid.Resources>
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Path=YourMemberNameHere, Converter={StaticResource DescriptionConverter}}"/>
    </DataGrid.Columns>
</DataGrid>