這篇文章主要介紹了C# 3.0中擴展方法怎么用,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
Extension Methods 使用擴展方法,使用的時候需要注意的地方
1.C# 3.0新特性中擴展方法所屬的類必須為靜態非泛型類,擴展方法也是靜態方法
2.***個參數為被擴展的類型實例,并且必須用this進行修飾
3.第二個參數開始對對應被擴展類型實例所傳遞的參數列表,即擴展類型實例
傳遞的***個參數對應擴展方法定義的第二個參數,依次類推
4.C# 3.0新特性中被擴展類型實例可像調用類型內部定義的實例方法一樣調用擴展方法
這里定義一個擴展方法:
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***個參數用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中擴展方法怎么用”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。