-
C#
通过反射获取类自定义特性描述列表
p>
OO
真的是个有趣的东西,我们都知道,创建类的时候,我们可以声
明属性
(property)
、字段
(
field)
等,而特性(
Attribute
)为人注意。在
.NET
中,特性使用,可分为
.NET
自带特性(如
Descriptio
n
)
和自定义特性。
由于需求需要,
本人粗浅研究了一下自定义特性的使用,
下面就返回类的自定义特性描述列表进行梳
理。
自定义特性类:
public
class
ImportHeaderAttribute
: ute
{
public
string
ImportHeader {
get
;
set
; }
public
int
Index {
get
;
set
; }
public
ImportHeaderAttribute(
string
header,
int
index)
{
ImportHeader = header;
Index = index;
}
}
获取类自定义特性描述列表方法:
///
///
获取类自定义特性描述列表
///
///
目标类
///
自定义特性类
///
自定义特性
///
排序特性
(
升序
)
,默认
null
不排序
///
返回类自定义特性描述列表,
Key:
属性
(
字段
< br>)
,
value:
特性描述
p>
public
static
<
br>(T).GetProperties())
IList
string
,
string
>>
GetDescriptionList
A>(
string
cusName,
string
index =
null
)
{
try
{
List
string
,
string
>> classList =
new
List
string
,
string
>>();
List
string
,
string
>> indexList =
new
List
string
,
string
>>();
string
key =
string
.Empty;
string
value =
string
.Empty;
#region
循环目标类属性
foreach
(PropertyInfo pro
in
typeof
//
循环目
标
类属性
{
var
attridures =
tomAttributes(
typeof
(A),
true
);
//
自
定义特性集合
key =
A a =
default
(A);
foreach
(
object
att
in
attridures)
{
a = (A)att;
p>
//
转换为自定义特性类对象
var
aInfo = e().GetProperty(
cusName);
//
获取对应特性
的属性对象
if
(aInfo !=
null
)
{
value =
ue(a).ToString();
(
new
KeyValuePair<
string
,
string
>(key,
valu
e));
//
赋值
}
if
(!
string
.IsNullOrEmpty(index))
{
var
aInfo2 =
e().GetProperty(index);
if
(aInfo2 !=
null
)
{
value
= ue(a).ToString();
(
new
KeyValuePair
<
string
,
string
>(key,
-
-
-
-
-
-
-
-
-
上一篇:北斗七星痣好不好,北斗七星痣有什么寓意
下一篇:修辞对偶是什么意思?举例说明