gpt4 book ai didi

c# - 如何读取枚举的文本值

转载 作者:行者123 更新时间:2023-11-30 20:05:18 29 4
gpt4 key购买 nike

我创建了一个枚举并想从中读取文本值。枚举如下:

public enum MethodID
{
/// <summary>
/// The type of request being done. Inquiry.
/// </summary>
[EnumTextValue("01")]
Inquiry,

/// <summary>
/// The type of request being done. Update
/// </summary>
[EnumTextValue("02")]
Update,
}

现在我想把枚举的值赋给一个请求对象methodID。我尝试了以下代码,但没有成功:

request.ID = Enum.GetName(typeof(MethodID), MethodID.Inquiry);  

我想要的是将值“01”分配给我将从 Enum MethodID 获取的请求数据协定 (request.ID) 的数据成员。我将如何得到这个?请帮忙

最佳答案

如果你只想获取 int 值,那么你可以将枚举声明为

public enum MethodID
{
[EnumTextValue("01")]
Inquiry = 1,

[EnumTextValue("02")]
Update = 2,
}

然后使用转换为 int:

ind id = (int)MethodID.Inquiry;

如果你想从属性中获取字符串值那么这是静态辅助方法

///<summary>
/// Allows the discovery of an enumeration text value based on the <c>EnumTextValueAttribute</c>
///</summary>
/// <param name="e">The enum to get the reader friendly text value for.</param>
/// <returns><see cref="System.String"/> </returns>
public static string GetEnumTextValue(Enum e)
{
string ret = "";
Type t = e.GetType();
MemberInfo[] members = t.GetMember(e.ToString());
if (members.Length == 1)
{
object[] attrs = members[0].GetCustomAttributes(typeof (EnumTextValueAttribute), false);
if (attrs.Length == 1)
{
ret = ((EnumTextValueAttribute)attrs[0]).Text;
}
}
return ret;
}

关于c# - 如何读取枚举的文本值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11644483/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com