姓谢的疯子

总是不知不觉的就陷入技术细节中了...

老外写的程序也不是那么完美啊:在C#中实现类似VBScript中Right()函数

http://www.csharphelp.com/archives4/archive616.html 上是这样写的:
        public static string Right(string param, int length)
        {
            //start at the index based on the lenght of the sting minus
            //the specified lenght and assign it a variable
            string result = param.Substring(param.Length - length, length);
            //return the result of the operation
            return result;
        }

假定字符串的长度是5位,而我们不知道这个字符串的长度,为了避免截断字符串,给 length 传了个6,这时就抛出 ArgumentOutOfRangeException 异常了。


我的代码如下:
public static string RightString(string sourceString, int length)
{
    return (sourceString.Length > length) ? sourceString.Substring(sourceString.Length - length) : sourceString;
}

posted on 2007-08-27 15:42  疯子谢  阅读(752)  评论(7)    收藏  举报

导航