我最近将一个 C# 项目从 .NET 3.5 升级到 .NET 4。我有一个方法可以从给定的MethodBase
实例列表中提取所有 MSTest 测试方法。它的身体是这样的:
return null == methods || methods.Count() == 0
? null
: from method in methods
let testAttribute = Attribute.GetCustomAttribute(method,
typeof(TestMethodAttribute))
where null != testAttribute
select method;
这在 .NET 3.5 中有效,但自从将我的项目升级到 .NET 4 后,此代码始终返回一个空列表,即使给定包含标记为方法的方法列表也是如此[TestMethod]
。.NET 4 中的自定义属性是否发生了变化?
调试时,我发现GetCustomAttributesData()
测试方法的结果给出了两个列表,CustomAttributeData
在 Visual Studio 2010 的“Locals”窗口中描述为:
Microsoft.VisualStudio.TestTools.UnitTesting.DeploymentItemAttribute("myDLL.dll")
Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute()
——这就是我要找的
但是,当我调用GetType()
第二个CustomAttributeData
实例时,我得到{Name = "CustomAttributeData" FullName = "System.Reflection.CustomAttributeData"} System.Type {System.RuntimeType}
. 我怎样才能TestMethodAttribute
摆脱CustomAttributeData
, 以便我可以从MethodBase
s 列表中提取测试方法?