我有一个扩展方法,多年来在WinForms中使用过,但是在尝试在新的WPF项目中使用时遇到了问题。该方法:
public static String GetDescription(this Enum value)
{
//var info = value.GetType().GetField(value.ToString());
//if (info != null)
//{
// var attributes = (DescriptionAttribute[])info.GetCustomAttributes(typeof(DescriptionAttribute), false);
// if (attributes != null && attributes.Length > 0)
// return attributes[0].Description;
//}
//return value.ToString();
var info = value.GetType().GetField(value.ToString());
var attributes = Attribute.GetCustomAttributes(info);
if (attributes.Length > 0 && (attributes[0] is System.ComponentModel.DescriptionAttribute))
return ((System.ComponentModel.DescriptionAttribute)attributes[0]).Description;
return value.ToString();
}
第一个块(被注释掉的)是原始方法。第二个块是我正在测试的稍微不同的版本。如果我强制执行带有转换的返回行,那么会出现此异常:
该对话框中异常的完整文本如下:附加信息: [A]System.ComponentModel.DescriptionAttribute 无法强制转换为[B]System.ComponentModel.DescriptionAttribute。类型A源自'System.ComponentModel.Primitives,Version=4.1.1.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a',位于'C:\TFS_Local\Antero\AnteroWPF\bin\Debug\System.ComponentModel.Primitives.dll'上下文中的“默认”位置。类型B源自“System,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089”在'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System\v4.0_4.0.0.0__b77a5c561934e089\System.dll'上下文中的“默认”位置。
涉及到的两个程序集似乎是:
System.ComponentModel.Primitives.dll(存在于构建bin目录中...不太确定它是如何到达那里的)
System.dll(出于明显的原因直接从GAC引用)
我完全迷失了。如果我移除ComponentModel DLL,那就会产生异常。即使异常声称System具有该类型,似乎也无法使用它。也就是说,在没有相应DLL的情况下,System.ComponentModel.DescriptionAttribute似乎不是有效的操作。
因此,如果我删除其中一个并失败了,而另一个则完全无法使用...那么为什么会出现这种异常?!
编辑: 我认为值得注意的是,如果我检查内存中的attributes值,我会发现数组确实有一个单一项,并且它是System.ComponentModel.DescriptionAttribute类型。