缺少自定义属性

时间:2015-12-14 06:32:18

标签: c# .net reflection custom-attributes

在C#中,可以使用反射通过m获取成员m.CustomAttributes上的属性(请参阅the documentation for this property)。但是,这种方法似乎错过了GetType的{​​{1}}方法的三个自定义属性(请参阅the Object in the Reference Source for .NET Framework 4.6.1):

Object
  

为什么这三个自定义属性不显示?

也许它与external方法的事实有关?

实际上,外在与它无关。

using System;
using System.Linq;
namespace ConsoleApplication1 {
  public class Program {
    public static void Main(string[] args) {
      var desiredCustomAttributes = typeof(object)
        .GetMethods()
        .First(m => m.Name == "GetType")
        .CustomAttributes
        .Select(ca => ca.ToString())
        .Where(s =>
          s.Contains("Pure") ||
          s.Contains("ResourceExposure") ||
          s.Contains("MethodImplAttribute"));
      var n = desiredCustomAttributes.Count();
      Console.WriteLine("Expected: 3");
      Console.WriteLine("  Actual: " + n); // prints "  Actual: 0"
      Console.ReadKey();
    }
  }
}

1 个答案:

答案 0 :(得分:1)

这不是因为该方法是外部的。尝试使用用户定义的类:

class MyAttr : Attribute { }
class Program
{
    [Pure]
    [ResourceExposure(ResourceScope.AppDomain)]
    [MethodImpl]
    [MyAttr]
    public void Foo() { }
}

.CustomAttributes仅返回MyAttr。我认为这仅仅是因为FCL不会将这三个属性作为自定义属性进行威胁。查看源代码,MethodInfo.CustomAttributes最终调用MetadataImport.EnumCustomAttributes,其中调用外部方法。

[SecurityCritical]
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void _Enum(IntPtr scope, int type, int parent, out MetadataEnumResult result);

我没有调试它,但我认为这个方法知道一些内置属性并从自定义属性中排除它们是有意义的。

编辑 PureAttributeResourceExposureAttribute是有条件建立的,这就是为什么你无法获得它们。

[Conditional("RESOURCE_ANNOTATION_WORK")]
public sealed class ResourceExposureAttribute : Attribute

[Conditional("CONTRACTS_FULL")]
public sealed class PureAttribute : Attribute

似乎MethodImplAttribute很特别。

相关问题