使用反射訪問屬性 MSDN

2022-02-11 02:41:57 字數 1952 閱讀 1750

如果沒有檢索自定義屬性的資訊和對其進行操作的方法,則定義自定義屬性並將其放置在源**中就沒有意義。c# 具有乙個反射系統,可用來檢索用自定義屬性定義的資訊。主要方法是 getcustomattributes,它返回物件陣列,這些物件在執行時等效於源**屬性。此方法具有多個過載版本。

屬性規範,如:

code

[author(

"h. ackerman

", version 

=1.1

)]class

sampleclass

在概念上等效於:

code

author anonymousauthorobject 

=new

author(

"h. ackerman");

anonymousauthorobject.version 

=1.1

;但是,直到查詢 sampleclass 以獲取屬性時才會執行此**。對 sampleclass 呼叫 getcustomattributes 會導致按上述方式構造並初始化乙個 author 物件。如果類還有其他屬性,則其他屬性物件的以類似方式構造。然後 getcustomattributes 返回 author 物件和陣列中的任何其他屬性物件。之後就可以對此陣列進行迭代,確定根據每個陣列元素的型別所應用的屬性,並從屬性物件中提取資訊。

示例

下面是乙個完整的示例。定義乙個自定義屬性,將其應用於若干實體並通過反射進行檢索。

code

[system.attributeusage(system.attributetargets.class 

|system.attributetargets.struct,

allowmultiple 

=true

)  //

multiuse attribute

]public

class

author : system.attribute

public

string

getname()

}[author(

"h. ackerman")]

private

class

firstclass

//no author attribute

private

class

secondclass

[author(

"h. ackerman

"), author(

"m. knott

", version 

=2.0

)]private

class

thirdclass

class

testauthorattribute

private

static

void

printauthorinfo(system.type t)

", t);

system.attribute attrs 

=system.attribute.getcustomattributes(t);  

//reflection

foreach

(system.attribute attr 

inattrs)

, version 

", a.getname(), a.version);}}

}}輸出

author information for firstclass

h. ackerman, version 1.00

author information for secondclass

author information for thirdclass

h. ackerman, version 1.00

m. knott, version 2.00

使用反射訪問屬性

using system using system.collections.generic using system.text namespace 使用反射訪問屬性 public string getname using system using system.collections.generic...

C 使用反射訪問特性

ms註解 如果沒有檢索自定義特性的資訊和對其進行操作的方法,則定義自定義特性並將其放置在源 中就沒有意義。使用反射,可檢索用自定義特性定義的資訊。主要方法是getcustomattributes,它返回物件陣列,這些物件在執行時等效於源 特性。此方法具有多個過載版本 例項 multiuse attr...

反射 屬性 介面的使用

using system using system.collections.generic using system.linq using system.text namespace entitytosqlns public inte ce ientity attributeusage attrib...