反射與特性

2021-08-20 11:18:14 字數 1684 閱讀 4070

反射

程式在執行時,可以檢視其它程式集或其本身的元資料。乙個執行的程式檢視本身的元資料或者其他程式集的元資料的行為叫做反射。

myclass.cs

class myclass// 定義乙個用來反射查詢的元資料

public void test()

}

program.cs

static void main(string args)

propertyinfo array1 = type.getproperties();//獲取型別的屬性列表

foreach (propertyinfo info in array1)

methodinfo array3 = type.getmethods();//獲取型別的方法列表

foreach (methodinfo info in array3)

console.readkey();

}

特性

特性(attribute)是一種允許我們向程式的程式集增加元資料的語言結構。它是用於儲存程式結構資訊的某種特殊型別的類。

[obsolete]:這個特性用來提示程式設計師這個方法過時,後面值設定true表示呼叫方法會報錯

[obsolete("方法過時了,請使用新方法",true)]

[conditional]:這個特性需要先引用using system.diagnostics;這個命名空間,作用是決定這個方法在程式中是否生效

[conditional("istest")]//#define istest//需要在開頭位置定義乙個巨集,使用巨集來決定是否呼叫test方法

[debuggerstepthrough]:可以跳過debugger的單步除錯,不讓進進入該方法

//引用using system.runtime.compilerservices;這個命名空間,輸出這個方法的檔案路徑,行數和方法名

static void printout(string str, [callerfilepath]string filename = "", [callerlinenumber]int linenumber = 0, [callermembername]string methodname = "")

自定義特性

//1.特性類的字尾以attribute結尾

//2.需要繼承自system.attribute

//3.一般情況下宣告為sealed

//4.一般情況下特性類用來表示目標結構的一些狀態(定義一些字段或者屬性,一般不定義方法)

[attributeusage(attributetargets.class)]中(.class)這個字尾用來表示這個特性類指定的目標

//(.method)表示這個特性類指定方法,(.property)這個特性類指定屬性

sealed class mytestattribute:system.attribute

public string versionnumber

public int id

public mytestattribute(string des)

}

在program中使用自定義特性

[mytest("hello",id =100)]//當我們使用特性類的時候字尾attribute不用寫

反射簡介 C 特性和反射

net編譯器的任務之一就是為所有定義和引用的型別生成元資料描述。除了程式集中標準的元資料外,net平台還支援特定 attribute 把更多的元資料嵌入到程式集中。net特性擴充套件了抽象的system.attribute基類,net中有很多預定義的特性,例如 dllimport obsolete ...

C 反射特性 一)

using system using system.collections.generic using system.linq using system.text using system.reflection namespace reflectionexam set private string ...

特性的使用,反射

1.自定義特性允許吧自定義元資料與元素關聯起來。這些元資料是在編譯過程中建立的,並嵌入到程式集中。反射是乙個普通術語,他描述了了在執行過程中檢查和處理程式元素的功能。反射可以完成以下任務 列舉型別的成員 例項化新物件 執行物件的成員 查詢型別的資訊 查詢程式集的資訊 檢查應用於某種型別的自定義特性 ...