MVC 中使用擴充套件方法

2022-03-04 03:00:46 字數 3622 閱讀 4924

擴充套件方法(extension method)是給那些不是你擁有、因而不能直接修改的類新增方法的一種方便的辦法。

一、使用擴充套件方法

1、定義乙個購物車的類-shoppingcart

1

using

system;

2using

system.collections;

3using

system.collections.generic;

4using

system.linq;

5using

system.web;67

namespace

demo.models816

}17 }

2、定義乙個擴充套件方法

1

using

system;

2using

system.collections.generic;

3using

system.linq;

4using

system.web;56

namespace

demo.models717

return

total;18}

28}29 }

this 關鍵字把totalprices定義為乙個擴充套件方法 shoppingcart 告訴。net 這個擴充套件方法運用與那個類

3、運用擴充套件方法

1

public

viewresult userextension()

2,//

皮划艇8

new product,//

休閒夾克

9new product,//

足球10

new product//

角旗11}12

};13

//求去購物車中的產品總價

14decimal carttotal = cart.totalprices();

15return view("

result

", (object)string.format("

total:

", carttotal));

16 }

4、結果展示

二、對介面運用擴充套件方法

1、在shoppingcart類中實現介面

1

using

system;

2using

system.collections;

3using

system.collections.generic;

4using

system.linq;

5using

system.web;67

namespace

demo.models812

public ienumeratorgetenumerator()

1316ienumerator ienumerable.getenumerator()

1720}

21 }

2、在介面上工作的擴充套件方法

1

using

system;

2using

system.collections.generic;

3using

system.linq;

4using

system.web;56

namespace

demo.models717

return

total;18}

19}20 }

3、將擴充套件方法運用於同一介面的不同實現

1

public

viewresult useextensionenumerable()

2,//

皮划艇7

new product,//

休閒夾克

8new product,//足球9

new product//

角旗10}11

};12 product productarary =,//

皮划艇14

new product,//

休閒夾克

15new product,//

足球16

new product//

角旗17

};18

//獲取購物車中的產品總價

19decimal carttotal =products.totalprices();

20//

獲取陣列中產品的總價

21decimal arraytotal =productarary.totalprices();

22return view("

result

",(object)string.format("

cart total:,array total:

",carttotal,arraytotal));

23 }

4、結果展示

三、建立過濾擴充套件方法

1、

1

using

system;

2using

system.collections.generic;

3using

system.linq;

4using

system.web;56

namespace

demo.models718

}19}20

}21 }

2、使用過濾擴充套件方法

1

public

viewresult usefilterextensionmethod()

2,//

皮划艇7

new product,//

休閒夾克

8new product,//足球9

new product//

角旗10}11

};12

decimal total = 0;13

foreach (product prod in products.filterbycategory("

soccer"))

1417

return view("

result

",(object)string.format("

total:

",total));

18 }

3、結果展示

只用soccer分類中的**被返回累加出來。

MVC5擴充套件方法

html.partial和html.renderpartial用法 html.partial和renderpartial的用法與區別 輸出方式 html.partial和renderpartial都是輸出html片段,區別在於 partial是將檢視內容直接生成乙個字串並返回 相當於有個轉義的過程 ...

mvc擴充套件

新增js引用 相對路徑 應用程式根目錄 js main.js public static mvchtmlstring renderjs this htmlhelper helper,params string paths var relativepath string.concat commonhe...

C 中使用MVC架構(三)

定義乙個基本業務邏輯介面ibaseservice,作各業務訪問的總中介,也就是說檢視層只通過ibaseservice的介面物件,訪問業務層,具體訪問哪個業務,是通過注入ibaseservice的實現類來完成的,可根據需要生成具體業務類,實現介面中定義的抽象方法。業務邏輯層通過對應資料實現類,訪問模型...