發表文章

目前顯示的是有「隨手筆記」標籤的文章

[隨手筆記]C#字串中的Right方法

改用C#好一段時間了,但是以前寫VB的習慣總是如影隨形的跟著。這沒什麼好或不好,以前說過,這年頭沒有雙語能力是不行的。 只是有時候我就是不很明白,為何VB有些簡單的字串方法C#怎麼也不肯加進來。不過,人家有人家的道理,我們則只能在變通當中找個繞路的方式。 我最近在C#程式碼中寫了十幾次字串的Right方法之後,終於下定決心乾脆改寫成 Extension methods ,說真的,Extension methods 是個好發明。 既然用了Extension methods,想說這麼常用的Method,網路上肯定有人寫的吧,隨手一找,居然有個 蒐集Extension methods的網站 ,真是有趣。網站上把常用的擴充方法都分門別類整理好,我要的 Right 當然也有囉。 改寫一下,加到公司的類別庫中: namespace ExtensionMethods { public static class MyExtensions { /// /// Returns the last few characters of the string with a length /// specified by the given parameter. If the string's length is less than the /// given length the complete string is returned. If length is zero or /// less an empty string is returned /// /// the string to process /// Number of characters to return /// public static string Right(this string s, int length) { length = Math.Max(length, 0); if (s.Length > length) { ...