新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
C# 3.0新特性:擴(kuò)展方法
Extension Methods 使用擴(kuò)展方法,使用的時候需要注意的地方

創(chuàng)新互聯(lián)基于分布式IDC數(shù)據(jù)中心構(gòu)建的平臺為眾多戶提供成都服務(wù)器托管 四川大帶寬租用 成都機(jī)柜租用 成都服務(wù)器租用。
1.C# 3.0新特性中擴(kuò)展方法所屬的類必須為靜態(tài)非泛型類,擴(kuò)展方法也是靜態(tài)方法
2.***個參數(shù)為被擴(kuò)展的類型實(shí)例,并且必須用this進(jìn)行修飾
3.第二個參數(shù)開始對對應(yīng)被擴(kuò)展類型實(shí)例所傳遞的參數(shù)列表,即擴(kuò)展類型實(shí)例
傳遞的***個參數(shù)對應(yīng)擴(kuò)展方法定義的第二個參數(shù),依次類推
4.C# 3.0新特性中被擴(kuò)展類型實(shí)例可像調(diào)用類型內(nèi)部定義的實(shí)例方法一樣調(diào)用擴(kuò)展方法
這里定義一個擴(kuò)展方法:
- public static class Extensions
- {
- public static bool Compare(this Customer customer1, Customer customer2)
- {
- if (customer1.CustomerId == customer2.CustomerId &&
- customer1.Name == customer2.Name &&
- customer1.City == customer2.City)
- {
- return true;
- }
- return false;
- }
- }
其中Compare***個參數(shù)用this修飾
完整源碼例子,這個例子主要查詢新建的newCustomer是否在列表List中
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace NewLanguageFeatures
- {
- public class Customer
- {
- public int CustomerId { get; private set; }
- public string Name { get; set; }
- public string City { get; set; }
- public Customer(int Id)
- {
- CustomerId = Id;
- }
- public override string ToString()
- {
- return Name + “\t” + City + “\t” + CustomerId;
- }
- }
- public static class Extensions
- {
- public static bool Compare(this Customer customer1, Customer customer2)
- {
- if (customer1.CustomerId == customer2.CustomerId &&
- customer1.Name == customer2.Name &&
- customer1.City == customer2.City)
- {
- return true;
- }
- return false;
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- var customers = CreateCustomers();
- var newCustomer = new Customer(10)
- {
- Name = “Stuart Glasson”,
- City = “Oxford”
- };
- foreach (var c in customers)
- {
- if (newCustomer.Compare(c))
- {
- Console.WriteLine(”The new customer was already in the list”);
- return;
- }
- }
- Console.WriteLine(”The new customer was not in the list”);
- }
- static List< Customer> CreateCustomers()
- {
- return new List< Customer>
- {
- new Customer(1) { Name = “Alex Roland”, City = “Berlin” },
- new Customer(2) { Name = “Oliver Cox”, City = “Marseille” },
- new Customer(3) { Name = “Maurice Taylor”, City = “London” },
- new Customer(4) { Name = “Phil Gibbins”, City = “London” },
- new Customer(5) { Name = “Tony Madigan”, City = “Torino” },
- new Customer(6) { Name = “Elizabeth A. Andersen”, City = “Portland” },
- new Customer(7) { Name = “Justin Thorp”, City = “London” },
- new Customer(8) { Name = “Bryn Paul Dunton”, City = “Portland” }
- };
- }
- }
C# 3.0新特性中的擴(kuò)展方法就介紹到這里,希望對大家有用。
【編輯推薦】
- C#語言讀書心得備忘
- 詳解C#制做Active控件的五個步驟
- 總結(jié)C#多線程的點(diǎn)點(diǎn)滴滴
- 學(xué)習(xí)C#多線程:lock的用法
- 各種C#數(shù)組的定義和初始化
網(wǎng)站題目:C# 3.0新特性:擴(kuò)展方法
分享URL:http://m.fisionsoft.com.cn/article/dhhshdh.html


咨詢
建站咨詢
