Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/259.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
具有字符串属性的C#枚举_C#_String_Properties_Enums - Fatal编程技术网

具有字符串属性的C#枚举

具有字符串属性的C#枚举,c#,string,properties,enums,C#,String,Properties,Enums,假设enum中有一些字符串,如下所示: enum MyEnum { stringA = "String a", stringB = "String b" } 然后,我尝试访问此枚举中字符串的字符串属性: MyEnum.stringA.Length 它不让我。我无法对枚举中的字符串使用任何字符串属性。是否可以访问这些字符串属性?还是我做错了什么 提前感谢。您可以使用System.ComponentModel命名空间中的DescriptionAtt

假设enum中有一些字符串,如下所示:

enum MyEnum
    {
        stringA = "String a",
        stringB = "String b"
    }
然后,我尝试访问此枚举中字符串的字符串属性:

MyEnum.stringA.Length
它不让我。我无法对枚举中的字符串使用任何字符串属性。是否可以访问这些字符串属性?还是我做错了什么


提前感谢。

您可以使用
System.ComponentModel
命名空间中的
DescriptionAttribute

enum MyEnum
{
    [Description("String a")]
    stringA,
    [Description("String b")]
    stringB
}
然后使用此方法获取描述:

public static string GetDescription(Enum Enumeration)
{
     string Value = Enumeration.ToString();
     Type EnumType = Enumeration.GetType();
     var DescAttribute = (DescriptionAttribute[])EnumType
            .GetField(Value)
            .GetCustomAttributes(typeof(DescriptionAttribute), false);
     return DescAttribute.Length > 0 ? DescAttribute[0].Description : Value;
}
您可以得到以下值:

var result = GetDescription(MyEnum.stringA).Length;

使用一个类。您不能对枚举执行此操作。您不允许使用字符串值声明枚举。“假设我的枚举中有一些字符串,如下所示”-假设您。你看,它不会工作,所以你可以忘记任何字符串操作之后。解释为什么要为枚举成员分配字符串值,也许有不同的方法。
classmyclass{publicstaticstringa=“stringA”publicstaticstringb=“stringB”}
然后使用
MyClass.stringA.Length
@NikolayKostov:Ick,no-这些是公共的,可写实例字段。
const
public static readonly
…您可以这样做,但取决于OP想要做什么,这可能是正确的解决方案,也可能不是。@CodeCaster我完全同意您在此处和问题中的评论。但是,OP没有解释他或她为什么需要这个。我想我的回答能帮上忙。