.net學習心得

來源:瑞文範文網 1.24W

1.反射:反射是中的重要機制,通過反射可以在運行時獲得中每一個類型,包括類、結構、委託和枚舉的成員,包括方法、屬性、事件,以及構造函數等。有了反射,既可以對每一個類型瞭如指掌。

.net學習心得

下面來演示一下反射的實例

(1)新建一個類庫項目。在解決方案上單擊右鍵選擇添加“新建項目”,在彈出來的框中選擇“類庫”,在下面名字欄中輸入classlib。然後刪除class1類,新添加一個類“classperson”,添加如下代碼:

namespace classlib

{

public class classperson

{

public classperson():this(null)

{

}

public classperson(string strname)

{

name = strname;

}

private string name;

private string sex;

private int age;

public string name

{

get { return name; }

set { name = value; }

}

public string sex

{

get { return sex; }

set { sex = value; }

}

public int age

{

get { return age; }

set { age = value; }

}

public void sayhello()

{

if (null==name)

eline("hello world");

else

eline("hello," + name);

}

}

}

添加完之後編譯生成一下,就會在這個類庫項目中的bindebug中有一個文件。然後添加一個控制檯應用程序。引入action的命名空間。添加的代碼如下:

using system;

using ric;

using ;

using ;

using ection;//添加反射的命名空間

namespace consoleapplication4

{

public class program

{

static void main(string[] args)

{

eline("列出程序集中的所有類型");

assembly ass = from("");

type[] mytype = ypes();

type classperson = null;

foreach (type p in mytype)

{

eline();

if (=="classperson")

{

classperson = p;

}

}

eline("列出classpersonl類中的所有的方法");

methodinfo[] md = ethods();

foreach(methodinfo m in md)

{

eline();

}

eline("實例化classperson類,並調用sayhello方法");

object obj = teinstance(classperson);

object objname=teinstance(classperson,"飛鷹");

methodinfo mysayhello = ethod("sayhello");

ke(obj, null);//無參數構造函數

ke(objname, null);//有參構造函數

key();

}

}

}

運行之後的結果是:

列出程序集中的所有類型

classperson

列出classpersonl類中的所有的方法

get_name

set_name

get_sex

set_sex

get_age

set_age

sayhello

tostring

equals

gethashcode

gettype

實例化classperson類,並調用sayhello方法

hello world

hello,飛鷹

g的作用

(1)引入命名空間,如:using system。

(2)using別名。

格式:using 別名=包括詳細命名空間信息的具體的類型

例如:在兩個命名空間(namespace1,namespace2)裏各有一個myclass類,這時可以這樣引入命名空間,

using aclass=ass;

using bclass=ass;

實例化時:

aclass my1=new aclass;

bclass my2=new bclass;

(3)using定義範圍

即時釋放資源,在範圍結束時處理對象。例如:

using(class1 cls1=new class1())

{

}

在這個代碼段結束時會觸發cls1的dispose方法釋放資源。

熱門標籤