【发布时间】:2016-03-19 13:53:15
【问题描述】:
在 C# 中,可以使用反射通过m.CustomAttributes 获取成员m 的属性(请参阅the documentation for this property)。但是,这种方法似乎遗漏了Object 的GetType 方法上的三个自定义属性(参见the Object in the Reference Source for .NET Framework 4.6.1):
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();
}
}
}
为什么这三个自定义属性不显示?
也许这与它是一个external 方法有关?
其实,身为外在与此无关。
using System;
using System.Linq;
using System.Runtime.Versioning;
namespace ConsoleApplication1 {
public class ResourceExposureAttributeOnConstructor {
[ResourceExposure(ResourceScope.None)]
public ResourceExposureAttributeOnConstructor() { }
}
public class Program {
public static void Main(string[] args) {
var n = typeof(object)
.GetConstructors()
.First()
.CustomAttributes
.Select(ca => ca.ToString())
.Where(s => s.Contains("ResourceExposure"))
.Count();
Console.WriteLine("Expected: 1");
Console.WriteLine(" Actual: " + n); // prints " Actual: 0"
Console.ReadKey();
}
}
}
【问题讨论】:
标签: c# .net reflection custom-attributes