检查酒店有属性 [英] Check if property has attribute
本文介绍了检查酒店有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
由于属性中的一类,与属性 - 什么是确定它是否包含给定的属性最快的方法是什么?例如:
Given a property in a class, with attributes - what is the fastest way to determine if it contains a given attribute? For example:
[IsNotNullable]
[IsPK]
[IsIdentity]
[SequenceNameAttribute("Id")]
public Int32 Id
{
get
{
return _Id;
}
set
{
_Id = value;
}
}
什么是确定例如,它拥有最快的方法IsIdentity属性?
What is the fastest method to determine that for example it has the "IsIdentity" attribute?
推荐答案
有在检索属性没有快速。但是,code应该是这样的(信贷Aaronaught):
There's no fast in retrieving attributes. But code ought to look like this (credit to Aaronaught):
var t = typeof(YourClass);
var pi = t.GetProperty("Id");
var hasIsIdentity = Attribute.IsDefined(pi, typeof(IsIdentity));
如果您需要检索属性的属性然后
If you need to retrieve attribute properties then
var t = typeof(YourClass);
var pi = t.GetProperty("Id");
var attr = (IsIdentity[])pi.GetCustomAttributes(typeof(IsIdentity), false);
if (attr.Length > 0) {
// Use attr[0], you'll need foreach on attr if MultiUse is true
}
这篇关于检查酒店有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文