C#學習筆記 ----反射

來源:互聯網
上載者:User

標籤:style   blog   color   io   使用   ar   資料   div   sp   

自訂特性允許把自訂中繼資料與程式元素關聯起來

 

.NET Framework允許使用者定義自己的特性

編譯器不能識別,但是特性應用於程式元素時,可以在編譯好的程式集中用作中繼資料

樣本:

public string SocialSecurityNumber{    get{        //etc.

 

屬性類別本身用一個特性 ----System.AttributeUsage特性來標記

AttributeUsage主要用於標識自訂特性可以應用到哪些類型的程式元素上

這些資訊由它的第一個參數給出,該參數必選,類型是枚舉類型AttributeTargets

其成員如下:

AllAssemblyClassConstructorDelegateEnumEventFieldGenericParameterInterfaceMethodModuleParameterPropertyReturnValueStruct

 

特性應用到整個程式集或模組中,Assembly和Module

樣本:

[assembly:SomeAssemblyAttribute(Parameters)][module:SomeAssemblyAttribute(Parameters)]

 

反射

Type實際上是一個抽象基類

 

擷取指向任何給定類型的Type引用有3種常用方式:

a.使用C#的typeof運算子

Typet = typeof(double);

b.使用GetType()方法,所有類都從System.Object繼承這個方法

double d = 10;Type t = d.GetType();

c.調用Type類的靜態方法GetType()

Type t = Type.GetType("System.Double");

 

Type是許多反射功能的入口

Type屬性:

Name  資料類型名

FullName  資料類型的完全限定名(包括名稱空間)

Namespace  在其中定義資料類型的名稱空間名

BaseType  該Type的直接基本類型

UnderlyingSystemType  該Type在.NET運行庫中映射到的類型

 

Type成員方法:

//返回物件類型    //方法ConstructorInfo    GetConstructor()、GetConstructors()EventInfo            GetEvent()、GetEvents()FieldInfo            GetField()、GetFields()InterfaceInfo    GetInterface()、GetInterfaces()MemberInfo    GetMember()、GetMembers()MethodInfo    GetMethod()、GetMethods()PropertyInfo    GetProperty()、GetProperties()

 

Assembly類在System.Reflection名稱空間中定義,它允許訪問給定程式集的中繼資料,它也包含可以載入和執行程式集的方法。

 

載入程式集,樣本:

Assembly assembly1 = Assembly.Load("SomeAssembly");Assembly assembly2 = Assembly.LoadFrom(@"C:\My Projects\Software\SomeOtherAssembly");

獲得在相應程式集中定義的所有類型的詳細資料,調用Assembly.GetType()方法

尋找自訂特性,GetCustomAttribute()

 

C#學習筆記 ----反射

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.