当运行下面的代码时,永远不会返回类型,尽管有一个类已分配了正确的属性。实际上,attr数组的长度始终为0。
Assembly a = Assembly.LoadFile(file);
foreach (Type t in a.GetTypes())
{
object[] attr = t.GetCustomAttributes(typeof(SchemeNameAttribute), false);
foreach (object attribute in attr)
{
SchemeNameAttribute schemeName = attribute as SchemeNameAttribute;
if (schemeName != null && schemeName.Name.ToLower() == brickName.ToLower() )
{
return t;
}
}
}
如果我将其更改为使用:
object[] attr = t.GetCustomAttributes(false);
然后它为Type选择一个类型为SchemeNameAttribute的自定义属性,但是
SchemeNameAttribute schemeName = attribute as SchemeNameAttribute;
始终为schemeName返回空值。
有什么想法吗?
答案 0 :(得分:2)
您混合了两个不同的加载程序集上下文:运行应用程序的“加载上下文”,以及使用LoadFile加载辅助程序集的“无上下文”。您想阅读this和that文章,以了解有关加载上下文的信息。这里最重要的部分是加载到不同上下文中的程序集,即使是来自同一位置,也被认为是不同的。因此,它们中的类型被认为是不同的。因此,在加载的程序集中键入SchemeNameAttribute与应用程序中的SchemeNameAttribute类型不同。
答案 1 :(得分:0)
我怀疑你已经重新声明了属性 - 即在两个程序集中(可能通过复制.cs)声明(单独)SchemeNameAttribute类型。这不起作用;类型由它们的程序集限定,因此Foo.dll中的SchemeNameAttribute是与Bar.dll / Bar.exe中的SchemeNameAttribute不同的类型。
您应该确保仅将SchemeNameAttribute类型声明一次 - 如有必要,可以将其移动到现有程序集都可以引用的dll。