C 的擴充套件方法詳解

2021-08-21 06:12:28 字數 3201 閱讀 3238

//必須是靜態類才可以新增擴充套件方法

static

class

program

//宣告擴充套件方法

//擴充套件方法必須是靜態的,add有三個引數

//this 必須有,string表示我要擴充套件的型別,stringname表示物件名

//三個引數this和擴充套件的型別必不可少,物件名可以自己隨意取如果需要傳遞引數,//再增加乙個變數即可

public

static

string

add(this

string stringname)

}

public

class

student

public

string

getstuinfo(string stuname, string stunum)

\n" +

"學號:", stuname, stunum);}}

public

static

class

extensionstudentinfo

//宣告擴充套件方法

//要擴充套件的方法必須是靜態的方法,add有三個引數

//this 必須有,string表示我要擴充套件的型別,stringname表示物件名

//三個引數this和擴充套件的型別必不可少,物件名可以自己隨意取如果需要傳遞引數,在此我們增加了兩個string型別的引數

public

static

string

extensiongetstuinfo(this student student, string stuname, string stunum)

}以上的工作做完之後便可以使用我們的擴充套件方法了,注意必須要用物件來呼叫擴充套件方法。

static

void

main(string args)

用途addcssclass()

新增class=」」屬性

generateid()

新增id,  會將id名稱中的"."替換為idattributedotreplacement 屬性值的字元.預設替換成"_"

mergeattribute()

新增乙個屬性,有多種過載方法.

setinnertext()

設定標籤內容, 如果標籤中沒有再巢狀標籤,則與設定innerhtml 屬性獲得的效果相同.

tostring()

輸出html標籤的字串, 帶有乙個引數的過載可以設定標籤的輸出形式為以下列舉值:

用途attributes

tag的所有屬性

idattributedotreplacement

新增id時替換"."的目標字元

innerhtml

tag的內部html內容

tagname

html標籤名, tagbuilder只有帶乙個引數-tagname的建構函式.所以tagname是必填屬性

public

static

string

span(this htmlhelper helper, string id, string text, string css, object htmlattributes)

=html.span(

"span.test",

"使用tagbuilder幫助構建擴充套件方法",

"colorred",

new)

%>

span

id="span-test"

class

="colorred"

style

="font-size: 15px;"

>使用tagbuilder幫助構建擴充套件方法

span

>

using system;

using system.collections.generic;

using system.linq;

using system.text;

using system.text.regularexpressions;

//宣告擴充套件方法的步驟:類必須是static,方法是static,

//第乙個引數是被擴充套件的物件,前面標註this。

//使用擴充套件方法的時候必須保證擴充套件方法類已經在當前**中using

namespace 擴充套件方法

//帶多個引數的擴充套件方法

//在原始字串前後加上指定的字元

public

static

string

quot(this

string _input, string _quot)

}}

(2)、使用方法

using system;

using system.collections.generic;

using system.linq;

using system.text;

namespace 擴充套件方法

}}

總結:

public

static

class

propertyextension

type t = self.gettype();

propertyinfo p = t.getproperty(propertyname);

return p.getvalue(self,

null);}}

str ="

abc"

;object

len 

=str.getvaluebyname(

"length");

ldstr

"length

"l_000d:

call

object

testlambda.propertyextension::getvaluebyname(

object

, string

)

c 擴充套件方法詳解

擴充套件方法被定義為靜態方法,但它們是通過例項方法語法進行呼叫的。它們的第乙個引數指定該方法作用於哪個型別,並且該引數以 this 修飾符為字首。擴充套件方法當然不能破壞物件導向封裝的概念,所以只能是訪問所擴充套件類的public成員。擴充套件方法使您能夠向現有型別 新增 方法,而無需建立新的派生型...

C 中的擴充套件方法詳解

擴充套件方法使你能夠向現有型別 新增 方法,而無需建立dezevgimo新的派生型別 重新編譯或以其他方式修改原始型別。擴充套件方法是一種特殊的靜態方法,但可以像擴充套件型別上的例項方法一樣進行呼叫。以上是msdn官網對擴充套件方法的描述,現在我通過乙個情景例子來對此進行闡釋。假設乙個控制台程式cl...

C 擴充套件方法和靜態類詳解

1.靜態方法屬於類,而普通方法則屬於物件,因此靜態方法可以用類名.靜態方法 來呼叫,而普通方法則必須用new來例項化後呼叫 2.靜態類中只能有 靜態的方法,屬性和變數 3.普通類中能有普通方法,也能有靜態類。在呼叫裡面的靜態方法時,可以使用普通類名.靜態方法來呼叫,不需要例項化類 擴充套件方法 擴充...