.NET 指南:参数的设计
生活随笔
收集整理的這篇文章主要介紹了
.NET 指南:参数的设计
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
本文中的這個指南有助于你為成員參數選擇正確的類型和名稱。下列文章同樣呈現了參數的設計指南。
- 枚舉與 Boolean 參數之間的選擇
- 使用可變數量的參數的成員。
- 指針參數
- 傳遞參數
- 驗證參量
使用最少被獲得的并通過成員來提供必需功能的變量類型。
下列代碼范例說明了這個指導方針。BookInfo 類繼承自 Publication 類。Manager 類實現了兩個方法:BadGetAuthorBiography 和 GoodGetAuthorBiography。BadGetAuthorBiography 使用了一個 BookInfo 對象的引用,盡管它只使用了在 Publication 里被聲明的成員。GoodGetAuthorBiography 方法示范了正確的設計。
// 擁有基本信息的類。 public class Publication {string author;DateTime publicationDate;public Publication(string author, DateTime publishDate){this.author = author;this.publicationDate = publishDate;}public DateTime PublicationDate{get {return publicationDate;}}public string Author{get {return author;}} }// 繼承自 Publication 的類 public class BookInfo :Publication {string isbn;public BookInfo(string author, DateTime publishDate, string isbn) :base(author, publishDate){this.isbn = isbn;}public string Isbn{get {return isbn;}} }public class Manager {// 這個方法沒有使用 Isbn 成員,因此它不需要 Books 的一個專門引用static string BadGetAuthorBiography(BookInfo book){string biography = "";string author = book.Author;// 在這里操作。return biography;}// 這個方法說明了正確的設計。static string GoodGetAuthorBiography(Publication item){string biography = "";string author = item.Author;// 在這里操作。return biography;} }不要使用被保留的參數。
庫的將來版本中能夠添加能夠獲取附加屬性的新重載。
下列代碼范例首先示范了一個違反了這個指導方針的錯誤方法,然后說明了另外一個正確被設計的方法。
public void BadStoreTimeDifference (DateTime localDate, TimeZone toWhere, Object reserved){// 在這里操作。}public void GoodCStoreTimeDifference (DateTime localDate, TimeZone toWhere) {// 在這里操作。 } public void GoodCStoreTimeDifference (DateTime localDate, TimeZone toWhere, bool useDayLightSavingsTime) {// 在這里操作 }不要公開暴露獲取指針、指針的數組,或者多維數組來作為參數的方法。
在使用大部分庫的時候,明白這些高級特征應該不是必須的。
把所有的輸出參數放到經值傳遞的參數和 ref 參數(排除參數的數組)的后面,即使這樣做導致了在重載之間的參數次序出現矛盾。
這個約定使方法的簽名更加容易被理解。
在成員重載或實現接口成員的時候保持一致的參數命名。
重載應該使用相同的參數名稱。重載應該使用與成員聲明相同的參數名稱。接口的實現應該使用在接口成員的簽名中被定義的相同名稱。
轉載于:https://www.cnblogs.com/Laeb/archive/2007/02/01/637394.html
總結
以上是生活随笔為你收集整理的.NET 指南:参数的设计的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#中类的继承问题04
- 下一篇: Reflector for .NET