jma*_*mac 5 .net c# reflection
我试图找出从属性中获取自定义属性的最佳方法。我一直在使用GetCustomAttributes()它,但是最近我读到它GetCustomAttributes()会导致创建该属性的实例,并且GetCustomAttributesData()仅获取有关该属性的数据而不必创建该属性的实例。
考虑到这一点,似乎GetCustomAttributesData()应该更快,因为它不会创建该属性的实例。但是,我在测试中没有看到预期的结果。在类中遍历属性时,第一次迭代GetCustomAttributes()运行大约6毫秒,GetCustomAttributesData()运行大约32毫秒。
有谁知道为什么要花GetCustomAttributesData()更长的时间?
我的主要目标是测试属性的存在,并忽略包含该属性的任何属性。我并不特别在乎我最终使用哪种方法,除了了解为什么GetCustomAttributesData()它比慢时,我并不真正关心哪种方法返回的结果GetCustomAttributes()。
这是我用来测试的一些示例代码。我通过注释掉一个然后再注释掉另一个独立地测试了这些if语句。
public static void ListProperties(object obj)
{
PropertyInfo[] propertyInfoCollection = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in propertyInfoCollection)
{
// This runs around 6ms on the first run
if (prop.GetCustomAttributes<MyCustomAttribute>().Count() > 0)
continue;
// This runs around 32ms on the first run
if (prop.GetCustomAttributesData().Where(x => x.AttributeType == typeof(MyCustomAttribute)).Count() > 0)
continue;
// Do some work...
}
}
public class MyCustomAttribute : System.Attribute
{
}
Run Code Online (Sandbox Code Playgroud)
不久前,IsDefined()在阅读本文后,我决定尝试该方法。它似乎比GetCustomAttributes()和都快GetCustomAttributesData()。
if (prop.IsDefined(typeof(MyCustomAttribute)))
continue;
Run Code Online (Sandbox Code Playgroud)
WellGetCustomAttributesData还创建了新对象的实例,而不是属性本身的实例。它创建CustomAttributeData 的实例。这个类主要有关于属性类型的信息,但也有关于构造函数和构造函数参数的信息,甚至还有构造函数参数的名称。
这些属性必须使用反射来设置,而创建属性实例只是一个标准的对象创建。当然,这一切都取决于你的属性的构造函数有多复杂,尽管一般我很少看到复杂的属性。
因此,调用GetCustomAttributesData为您提供了更多/不同的关于属性的信息,而不是GetCustomAttributes(对于简单属性)更昂贵的操作。
但是,如果您打算GetCustomAttributesData在同一个MemberInfo对象上多次调用它可能会更快,因为反射调用通常会被缓存。但是我没有对此进行基准测试,因此请稍加注意。
| 归档时间: |
|
| 查看次数: |
1479 次 |
| 最近记录: |