【发布时间】:2014-11-24 15:29:21
【问题描述】:
为了尽量简短,我创建了以下枚举
public enum Frequency
{
[Description("Monthly")]
Monthly,
[Description("Quarterly")]
Quarterly,
[Description("N/A")]
NA
}
然后我有一个使用相同描述字符串的组合框。
当我选择一个新选项时,特别是“N/A”选项,它无法正确读取。
我用来根据传入的字符串搜索正确枚举的代码是...
/// Returns an enum of the specified type that matches the string value passed in. Note this does ignore case
<param name="value">The string value.</param>
public static TEnum GetEnum<TEnum>(string value)
{
if (string.IsNullOrEmpty(value))
{
// Default not set value name
value = "None";
}
return (TEnum)System.Enum.Parse(typeof(TEnum), value.Replace(" ", string.Empty), true);
}
所以当 value = "N/A" 时,我得到以下错误..
"An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll"
附加信息:未找到请求的值 'N/A'。"
我似乎无法理解为什么会发生这种情况。还有另一个预先存在的组合框,其中 decriction 还包含一个“/”字符,并且会发生相同的错误。所以这似乎不是我做错了什么,而只是枚举字符串检查的行为。
任何有关这导致问题的原因的见解将不胜感激。 :) 谢谢!
编辑: 更多信息..
所以这是触发枚举搜索的代码..
if (this.FrequencyCombo.SelectedItem != null && !this.FrequencyCombo.SelectedItem.Equals(Utilities.GetDescription(currentLoan.Frequency)))
{
currentLoan.Frequency = Utilities.GetEnum<Frequency>(this.FrequencyCombo.SelectedItem.ToString());
}
【问题讨论】:
-
检查的是名称 (NA),而不是描述 (N/A)。
-
显示的代码中没有任何内容表明完全使用了描述。
-
为什么你没有让文本使用
Description,但是你的组合值是枚举值。 -
感谢到目前为止的 cmets!我已经添加了一段额外的代码来做'GetEnum'检查。也许这有帮助。当我在调试器中时,我到达行 return (TEnum)System.Enum.Parse(typeof(TEnum), value.Replace(" ", string.Empty), true);当我将鼠标悬停在“值”变量上时,它肯定显示为“N/A”。所以你的意思是希望通过“NA”,而不是“N/A”?