[隨手筆記]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)
            {
                return s.Substring(s.Length - length, length);
            }
            else
            {
                return s;
            }
        }
    }
}

終於,有可愛的string.Right可以用囉...
以後只需要像底下這樣寫:
using ExtensionMethods;
...
string result;
result = ("abc"+"def").Right(5);
就可以啦...

----------------------------------------
筆記:
1.Extension methods 是個好發明
2.http://www.extensionmethod.net是個好網站
3.以後再也不要重複寫Right Method了...

留言

匿名表示…
public static string Right(this string param, int length)
{
return param.Substring(param.Length - length, length);
}

這個網誌中的熱門文章

使用 Airtable 在小型需求上取代傳統資料庫

在POC或迷你專案中使用 LiteDB

專業的價值...

精彩(且驚人)的Semantic Kernel入門範例

周末讀書會 - 一如既往