【发布时间】:2010-10-21 03:27:17
【问题描述】:
我有以下情况,当我尝试投射时抛出异常:
- 我添加了项目引用并导入了项目的命名空间。
- LoadFile 行加载构建此项目时生成的 dll。
- 我正在尝试访问从 dll 中装饰对象属性的属性的公共字段。
- 这里是异常文本:
[A]MyNamespace.PropertyMetaDataAttribute 无法转换为 [B]MyNamespace.PropertyMetaDataAttribute。类型 A 源自位置“C:\projectA\bin\debug\A.dll”的上下文“LoadFrom”中的“A,版本=12.0.0.25,Culture=neutral,PublicKeyToken=null”。类型 B 源自 'A, Version=12.0.0.25, Culture=neutral, PublicKeyToken=null' 在位置 'C:\currentProject\bin\debug\A.dll' 的上下文 'Default' 中。
代码sn-p:
using MyNamespace; // added project reference to this item
m_Assembly = Assembly.LoadFile(ConfigurationManager.AppSettings["DLL_File_Path"]);
Type objectType = m_Assembly.GetType(string.Format("{0}.{1}", NAMESPACE_PREFIX, "MyObject"));
// Crash happens on line below:
Attribute attr = (Attribute) objectType.GetProperty("Name").GetCustomAttributes(false)[0];
//This is the layout of the object which has the property
MyObject
{
[MyAttribute(Name="FooName")]
Foo {get;set;}
}
// This is the definition of the attribute
MyAttribute :Attribute
{
// Want to access the value
public string Name = string.Empty;
}
【问题讨论】:
标签: .net reflection