屬性和反射

Metadata is information about the data that is information about the types ,code, assembly and so forth stored along with the program.Attributes are a mechanism for adding metadata,such as compiler instructions and other data about your data,methods and classes, to the program itself.

An attribute is an object that represents data you want to associate with an element in your program .The element to which you attach an attribute is referred as the target of the attribute.

 

1.屬性目標

屬性有作用對象的種類,這稱爲屬性目標。在AttributeTargets中聲明

2.使用屬性

放在方括號裏面,並緊貼作用的元素之前,作用於assembly的除外,要放在文件頭部(using語句之後)。可以並列排放組合,也可以使用逗號分隔。

3.自定義屬性--直接看代碼

4.反射

反射主要有4種用途-1.查看元數據  2.進行類型發現  3.對方法和properties的遲綁定  4.運行時創建新類型

4.1查看元數據

Type類是反射類的核心,provided to discover the attribute of a member and provide access to the metadata.Type encapsulate a representation of the type of an object.The Type class the primary way to access metadata.Type encapsulates information about the member of a class(eg. fields,methods,properties,events,etc).

4.2 類型發現

This allows you to examine the types in an assembly and interact with or instantiate those types. You can use reflection to explore and examine the contents of an assembly.You can find the types associated with a module;the methods,fields,properties,and events associated with a type,as well as the signatures of each of the type`s methods;the interfaces supported by the type;and the type`s base class.

查看一個類型的所有成員

僅查找方法

指定查找

4.3 對方法和properties的遲綁定

allows the programmer to invoke properties and methods on objects dynamically instantiated,based on type discovery.This in also known as dynamic invocation.

可能需要使用Activator動態加載一個類的實例,如果對於一個靜態的類則不需要。解釋一下:

1.首先獲得類型,

2.然後獲得方法,傳入函數原型

3.準備好方法的參數

4.調用,注意第一個參數,如果是靜態類型,傳入靜態類型的type,否則要傳入instance的名字。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章