查找带有自定义属性标记的类不起作用

本文关键字:不起作用 自定义属性 查找 | 更新日期: 2023-09-27 18:02:20

我使用了另一个答案中的代码来查找程序集中标记有特定自定义属性的类:

var allClasses = tpAssy.GetTypes();
var testClasses = from t in tpAssy.GetTypes()
                  let attributes = t.GetCustomAttributes(typeof(TestClassAttribute), true)
                  where attributes != null && attributes.Length > 0
                  select new { Type = t, Attributes = attributes.Cast<TestClassAttribute>() };
然而,在我的测试用例程序集中,我可以看到allClasses列出了4个类,其中三个用我感兴趣的自定义属性(TestClassAttribute)标记。但是第二个分配给testClasses的Linq查询返回一个空枚举。 下面是这样一个类的代码头:
[TestClass()]
public class BaseSessionTest
{...

这是VS2013与。net 4.5。

给了什么?

查找带有自定义属性标记的类不起作用

这是。net框架的问题。正在加载的程序集是使用Visual Studio 2008(。.Net 3.5),而无法运行的应用程序是Visual Studio 2013中的。Net 4.6。在后一种情况下,反射显然不能完全与使用早期框架编译的。net程序集一起工作。这是一个bug还是一个你必须知道的秘密技巧?