【发布时间】:2013-03-06 05:34:19
【问题描述】:
我有一个枚举,用于查找协调字符串值。其中一个枚举中有一个空格,因此我试图使用 description 属性来查找该值。在找到 DescriptionAttribute 后,我无法转换回公共类。
public class Address
{
...blah...more class datatypes here...
public AddressType Type { get; set; }
...blah....
}
public enum AddressType
{
FRA = 0,
JAP = 1,
MEX = 2,
CAN = 3,
[Description("United States")]
UnitedStates = 4,
}
if (Address.Type.ToString() == "UnitedStates")
{
Adddress.Type = GetDescription(Address.Type);
}
private static AddressType GetDescription(AddressType addrType)
{
FieldInfo fi = addrType.GetType().GetField(addrType.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi.GetCustomAttributes(
typeof(DescriptionAttribute), false);
return (attributes.Length > 0) ? attributes[0].Description : addrType.ToString();
}
在 GetDescription 方法中,我如何将它转换回其公共类数据类型“AddressType”,因为这里它是一个字符串,所以它失败了?
【问题讨论】:
-
枚举是
AddrType,但是你给你的方法传递了AddressType类型的参数。当您的方法的返回类型为AddressType时,您还尝试返回string。 -
很抱歉应该提到枚举是另一个公共类的一部分,见上文。
-
您仍然会遇到问题(至少考虑到您发布的代码),因为类型名称不匹配(
AddressTypevsAddrType)和方法的返回类型你提供的不是string。 -
这就是我遇到的问题是字符串。我需要将其转换回 AddressType,addrType 只是我认为的本地名称。
-
所以你想通过一个
AddressType到方法中得到string的描述,然后再转换回原来的AddressType?为什么?