Skip to main content
 首页 » 编程设计

c#之.NET 4 中的自定义属性更改

2024年02月24日30xxx_UU

我最近将一个 C# 项目从 .NET 3.5 升级到 .NET 4。我有一个方法可以从 MethodBase 的给定列表中提取所有 MSTest 测试方法。实例。它的 body 看起来像这样:

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 的“本地”窗口中将其描述为:

  1. Microsoft.VisualStudio.TestTools.UnitTesting.DeploymentItemAttribute("myDLL.dll")
  2. Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute() -- 这就是我要找的

当我调用 GetType()在那一秒CustomAttributeData但是,例如,我得到 {Name = "CustomAttributeData" FullName = "System.Reflection.CustomAttributeData"} System.Type {System.RuntimeType} .我怎样才能得到 TestMethodAttribute来自 CustomAttributeData , 这样我就可以从 MethodBase 的列表中提取测试方法是吗?

请您参考如下方法:

你用过吗

method.GetCustomAttributes(typeof(TestMethodAttribute), false) 

相反?向目标询问自定义属性通常是我获取它们的方式。

这是一个草率的例子:

using System; 
using System.Linq; 
 
[AttributeUsage(AttributeTargets.All)] 
public class FooAttribute : Attribute {} 
 
class Test 
{ 
    static void Main() 
    { 
        var query = typeof(Test).GetMethods() 
            .Where(method => method.GetCustomAttributes( 
                              typeof(FooAttribute), false).Length != 0); 
 
        foreach (var method in query) 
        { 
            Console.WriteLine(method); 
        } 
    } 
 
    [Foo] 
    public static void MethodWithAttribute1() {} 
 
    [Foo] 
    public static void MethodWithAttribute2() {} 
 
    public static void MethodWithoutAttribute() {} 
 
}