具有字符串属性的C#枚举
假设enum中有一些字符串,如下所示:具有字符串属性的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 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没有解释他或她为什么需要这个。我想我的回答能帮上忙。