給 c# 程序員的十個(gè)重要提示
本文講述我認(rèn)為對(duì) c# 程序員最重要的 10 個(gè)提示, 每個(gè)提示都會(huì)有一段對(duì)應(yīng)的代碼, 對(duì) 新手來說也很容易掌握。
1: 為非公開的方法編寫測(cè)試
你嘗試過為組件的非公開方法寫測(cè)試么? 很多開發(fā)者都沒有寫過, 因?yàn)檫@些方法對(duì)測(cè)試項(xiàng) 目來說是不可見的。 c# 可以通過在 AssemblyInfo.cs 中添加下面的標(biāo)記 (InternalsVisibleToAttribute) , 讓內(nèi)部成員對(duì)其它組件可見。
//Make the internals visible to the test assembly [assembly: InternalsVisibleTo("MyTestAssembly")]
2: 使用 Tuples 類型
曾經(jīng)見到過有人僅僅因?yàn)楹瘮?shù)要返回多個(gè)值而創(chuàng)建了一個(gè) POCO 類, 其實(shí) .Net 4.0 中的 Tuples 類型會(huì)更加適用, 例如:
public Tuple<int, string, string> GetEmployee() { int employeeId = 1001; string firstName = "Rudy"; string lastName = "Koertson"; //Create a tuple and return return Tuple.Create(employeeId, firstName, lastName); }
3: 用 yield 替代臨時(shí)集合
從集合中選出部分成員時(shí), 通常會(huì)創(chuàng)建一個(gè)臨時(shí)集合/列表來保存成員并返回, 例如下面 的代碼:
public List<int> GetValuesGreaterThan100(List<int> masterCollection) { List<int> tempResult = new List<int>(); foreach (var value in masterCollection) { if (value > 100) { tempResult.Add(value); } } return tempResult; }
要避免這樣的臨時(shí)集合, 可以使用 yield 關(guān)鍵字, 示例如下:
public IEnumerable<int> GetValuesGreaterThan100(List<int> masterCollection) { foreach (var value in masterCollection) { if (value > 100) { yield return value; } } }
當(dāng)然, 也可是使用 LINQ 來解決上面的問題。
4: 告訴別人你將替換一個(gè)方法
當(dāng)你有一個(gè)組件時(shí), 并且你打算替換其中的一個(gè)方法時(shí), 可以先為方法添加過時(shí)標(biāo)記以通 知客戶端, 示例代碼如下:
[Obsolete("This method will be deprecated soon. You could use XYZ alternatively.")] public void MyComponentLegacyMethod() { //Here is the implementation }
使用這個(gè)方法客戶端在編譯時(shí)會(huì)發(fā)出一個(gè)警告, 如果你不再允許客戶端使用過時(shí)的方法時(shí), 可以為過時(shí)標(biāo)記添加一個(gè)額外的布爾參數(shù), 在下面的例子中, 客戶但程序?qū)⒕幾g失?。?/p>
[Obsolete("This method is deprecated. You could use XYZ alternatively.", true)] public void MyComponentLegacyMethod() { //Here is the implementation }
5: 牢記 LINQ 查詢是延遲執(zhí)行的
在 .NET 中編寫 LINQ 查詢時(shí), 只有當(dāng)你訪問 LINQ 查詢的結(jié)果時(shí), LINQ 查詢才會(huì)被執(zhí) 行, LINQ 的這種特征被稱為延遲執(zhí)行, 不過值得注意的是每訪問一次結(jié)果, LINQ 查詢 都會(huì)被執(zhí)行一次。
為了避免重復(fù) LINQ 查詢的重復(fù)執(zhí)行, 可以先將查詢轉(zhuǎn)換成列表, 如下所示:
public void MyComponentLegacyMethod(List<int> masterCollection) { // 在下面示例中, 如果沒有調(diào)用 ToList , LINQ 查詢將會(huì)被執(zhí)行兩次 var result = masterCollection.Where(i => i > 100).ToList(); Console.WriteLine(result.Count()); Console.WriteLine(result.Average()); }
6: 使用 explicit 關(guān)鍵字轉(zhuǎn)換業(yè)務(wù)實(shí)體類型
使用 explicit 關(guān)鍵字來定義業(yè)務(wù)實(shí)體類型之間的轉(zhuǎn)換, 當(dāng)代碼中出現(xiàn)類型轉(zhuǎn)換請(qǐng)求時(shí), 轉(zhuǎn)換方法會(huì)自動(dòng)執(zhí)行, 下面是示例代碼:
class Program { static void Main(string[] args) { var entity = new ExternalEntity { Id = 1001, FirstName = "Dave", LastName = "Johnson" }; var convertedEntity = (MyEntity)entity; } } class MyEntity { public int Id { get; set; } public string FullName { get; set; } public static explicit operator MyEntity(ExternalEntity externalEntity) { return new MyEntity { Id = externalEntity.Id, FullName = externalEntity.FirstName + " " + externalEntity.LastName }; } } class ExternalEntity { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } }
7: 保持異常的原始堆棧跟蹤
在 c# 代碼中, 如果你像下面的代碼一樣在 catch 代碼塊中拋出 ConnectDatabase 方法中出現(xiàn)的異常, 異常的堆棧就會(huì)只顯示到 RunDataOperation 方法, 這樣就會(huì)丟失 異常原始的堆棧跟蹤信息導(dǎo)致不能找到確切的錯(cuò)誤源頭。
public void RunDataOperation() { try { Intialize(); ConnectDatabase(); Execute(); } catch (Exception exception) { throw exception; } }
保持原始堆棧跟蹤的代碼如下:
public void RunDataOperation() { try { Intialize(); ConnectDatabase(); Execute(); } catch (Exception) { throw; } }
8: 使用 Flags 標(biāo)記將枚舉作為位域處理
在 c# 中為枚舉類型添加 Flags 標(biāo)記可以將枚舉作為位域(即一組標(biāo)志)處理, 這樣可 以對(duì)枚舉值進(jìn)行自由組合, 示例代碼如下:
class Program { static void Main(string[] args) { int snakes = 14; Console.WriteLine((Reptile)snakes); } } [Flags] enum Reptile { BlackMamba = 2, CottonMouth = 4, Wiper = 8, Crocodile = 16, Aligator = 32 }
上面代碼的輸出為 “BlackMamba, CottonMouth, Wiper” , 如果沒有 Flags 標(biāo)記, 則上 面的輸出為 14 。
9: 為泛型添加類型約束
創(chuàng)建泛型類型時(shí), 需要指定提供的泛型類型必須實(shí)現(xiàn)指定的參數(shù)或者繼承自特定的基類時(shí), 可以這樣做:
class MyGenricClass<T> where T : IMyInterface { //Body of the class come in here }
當(dāng)然, 也可以在方法級(jí)別這樣做:
class MyGenricClass { public void MyGenericMethod<T>(T t) where T : IMyInterface { //Generic implementation goes in here } }
10: IEnumerable 類型不能確保只讀
在你創(chuàng)建的類型中, 暴露了一個(gè)類型為 IEnumerable 的只讀屬性, 但是調(diào)用者依然可 以通過類型轉(zhuǎn)換來修改屬性的內(nèi)容, 比如這樣:
class Program { static void Main(string[] args) { MyClass myClass = new MyClass(); ((List<string>)myClass.ReadOnlyNameCollection).Add("######From Client#####"); myClass.Print(); } } class MyClass { List<string> _nameCollection = new List<string>(); public MyClass() { _nameCollection.Add("Rob"); _nameCollection.Add("John"); _nameCollection.Add("Jummy"); _nameCollection.Add("Derek"); } public IEnumerable<string> ReadOnlyNameCollection { get { return _nameCollection.AsEnumerable(); } } public void Print() { foreach (var item in ReadOnlyNameCollection) { Console.WriteLine(item); } } }
上面的代碼修改了列表, 添加了一個(gè)新項(xiàng)目, 要避免這種情況, 應(yīng)使用 AsReadOnly 而不是 AsEnumerable :
public IEnumerable<string> ReadOnlyNameCollection { get { return _nameCollection.AsReadOnly(); } }
以上就是給 c# 程序員的十個(gè)重要提示的詳細(xì)內(nèi)容,更多關(guān)于c# 程序員的十個(gè)重要提示的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- c# 設(shè)置TeeChart控件的提示文本
- C#瀏覽器提示跨域問題解決方案
- C#實(shí)現(xiàn)倒計(jì)時(shí)關(guān)閉提示框功能
- C#實(shí)現(xiàn)狀態(tài)欄提示信息功能的示例
- C# winForm實(shí)現(xiàn)的氣泡提示窗口功能示例
- 解決C#調(diào)用dll提示
- C#實(shí)現(xiàn)簡(jiǎn)單的loading提示控件實(shí)例代碼
- c#消息提示框messagebox的詳解及使用
- C#中TextBox實(shí)現(xiàn)輸入提示功能的方法
- C#程序提示“正由另一進(jìn)程使用,因此該進(jìn)程無法訪問該文件”的解決辦法
- C#提示:“在證書存儲(chǔ)區(qū)中找不到清單簽名證書”的解決方法
- c# 關(guān)閉窗體時(shí)提示的小例子
相關(guān)文章
C# 中 System.Index 結(jié)構(gòu)體和 Hat 運(yùn)算符(^)的使用示例
這篇文章主要介紹了C# 中 System.Index 結(jié)構(gòu)體和 Hat 運(yùn)算符(^)的使用示例,幫助大家更好的理解和使用C#,感興趣的朋友可以了解下2020-09-09C# 構(gòu)造函數(shù)如何調(diào)用虛方法
這篇文章主要介紹了C# 構(gòu)造函數(shù)如何調(diào)用虛方法,文中講解非常詳細(xì),示例代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下2020-07-07c#模擬js escape方法的簡(jiǎn)單實(shí)例
這篇文章主要介紹了c#模擬js escape方法的簡(jiǎn)單實(shí)例,有需要的朋友可以參考一下2013-11-11c# 判斷指定文件是否存在的簡(jiǎn)單實(shí)現(xiàn)
這篇文章主要介紹了c# 判斷指定文件是否存在的簡(jiǎn)單實(shí)現(xiàn),需要的朋友可以參考下2014-02-02