• .NET常用操作小知识


    一、.NET截取指定长度汉字超出部分以“.....”表示

    /// <summary> 
    /// 将指定字符串按指定长度进行剪切, 
    /// </summary> 
    /// <param name= "oldStr "> 需要截断的字符串 </param> 
    /// <param name= "maxLength "> 字符串的最大长度 </param> 
    /// <param name= "endWith "> 超过长度的后缀 </param> 
    /// <returns> 如果超过长度,返回截断后的新字符串加上后缀,否则,返回原字符串 </returns> 
    public static string StringTruncat(string oldStr, int maxLength, string endWith) 
    { 
    if (string.IsNullOrEmpty(oldStr)) 
    // throw new NullReferenceException( "原字符串不能为空 "); 
    return oldStr + endWith; 
    if (maxLength < 1) 
    throw new Exception("返回的字符串长度必须大于[0] "); 
    if (oldStr.Length > maxLength) 
    { 
    string strTmp = oldStr.Substring(0, maxLength); 
    if (string.IsNullOrEmpty(endWith)) 
    return strTmp; 
    else 
    return strTmp + endWith; 
    } 
    return oldStr; 
    }
    View Code

    调用:

     var v = StringTruncat("广东省深圳市西乡镇宝安区", 10, "...");

    显示:广东省深圳市西乡镇宝...

    二、过滤SQL非法字符串

    /// <summary> 
    /// 过滤SQL非法字符串 
    /// </summary> 
    /// <param name="value"></param> 
    /// <returns></returns> 
    public static string Filter(string value) 
    { 
    if (string.IsNullOrEmpty(value)) 
    return string.Empty; 
    value = Regex.Replace(value, @";", string.Empty); 
    value = Regex.Replace(value, @"'", string.Empty); 
    value = Regex.Replace(value, @"&", string.Empty); 
    value = Regex.Replace(value, @"%20", string.Empty); 
    value = Regex.Replace(value, @"--", string.Empty); 
    value = Regex.Replace(value, @"==", string.Empty); 
    value = Regex.Replace(value, @"<", string.Empty); 
    value = Regex.Replace(value, @">", string.Empty); 
    value = Regex.Replace(value, @"%", string.Empty); 
    return value; 
    }
    View Code

    三、穿过代理服务器取远程用户真实IP地址:

    if(Request.ServerVariables["HTTP_VIA"]!=null)
    {
      string user_IP=Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
    }
    else
    {
      string user_IP=Request.ServerVariables["REMOTE_ADDR"].ToString();
    }
    View Code

    四、sql server中 len和datalength区别

    select len('a好')  //返回为2
    select datalength('a好')  //返回为3

    五、截取指定字节长度的字符串扩展方法

    public static class Extension
    {
          /// <summary>
            /// 截取指定字节长度的字符串
            /// </summary>
            /// <param name="str">原字符串</param>
            /// <param name="len">截取字节长度</param>
            /// <returns></returns>
            public static string CutByteString(this string str, int len)
            {
                string result = string.Empty;// 最终返回的结果
                if (string.IsNullOrEmpty(str)) { return result; }
                int byteLen = System.Text.Encoding.Default.GetByteCount(str);// 单字节字符长度
                int charLen = str.Length;// 把字符平等对待时的字符串长度
                int byteCount = 0;// 记录读取进度
                int pos = 0;// 记录截取位置
                if (byteLen > len)
                {
                    for (int i = 0; i < charLen; i++)
                    {
                        if (Convert.ToInt32(str.ToCharArray()[i]) > 255)// 按中文字符计算加2
                        { byteCount += 2; }
                        else// 按英文字符计算加1
                        { byteCount += 1; }
                        if (byteCount > len)// 超出时只记下上一个有效位置
                        {
                            pos = i;
                            break;
                        }
                        else if (byteCount == len)// 记下当前位置
                        {
                            pos = i + 1;
                            break;
                        }
                    }
                    if (pos >= 0)
                    { result = str.Substring(0, pos); }
                }
                else
                { result = str; }
                return result;
            }
    
    
            /// <summary>
            /// 截取指定字节长度的字符串
            /// </summary>
            /// <param name="str">原字符串</param>
            /// <param name="startIndex">起始位置</param>
            /// <param name="len">截取字节长度</param>
            /// <returns></returns>
            public static string CutByteString(this string str, int startIndex, int len)
            {
                string result = string.Empty;// 最终返回的结果
                if (string.IsNullOrEmpty(str)) { return result; }
    
                int byteLen = System.Text.Encoding.Default.GetByteCount(str);// 单字节字符长度
                int charLen = str.Length;// 把字符平等对待时的字符串长度
    
                if (startIndex == 0)
                { return CutByteString(str, len); }
                else if (startIndex >= byteLen)
                { return result; }
                else //startIndex < byteLen
                {
                    int AllLen = startIndex + len;
                    int byteCountStart = 0;// 记录读取进度
                    int byteCountEnd = 0;// 记录读取进度
                    int startpos = 0;// 记录截取位置                
                    int endpos = 0;// 记录截取位置
                    for (int i = 0; i < charLen; i++)
                    {
                        if (Convert.ToInt32(str.ToCharArray()[i]) > 255)// 按中文字符计算加2
                        { byteCountStart += 2; }
                        else// 按英文字符计算加1
                        { byteCountStart += 1; }
                        if (byteCountStart > startIndex)// 超出时只记下上一个有效位置
                        {
                            startpos = i;
                            AllLen = startIndex + len - 1;
                            break;
                        }
                        else if (byteCountStart == startIndex)// 记下当前位置
                        {
                            startpos = i + 1;
                            break;
                        }
                    }
    
                    if (startIndex + len <= byteLen)//截取字符在总长以内
                    {
                        for (int i = 0; i < charLen; i++)
                        {
                            if (Convert.ToInt32(str.ToCharArray()[i]) > 255)// 按中文字符计算加2
                            { byteCountEnd += 2; }
                            else// 按英文字符计算加1
                            { byteCountEnd += 1; }
                            if (byteCountEnd > AllLen)// 超出时只记下上一个有效位置
                            {
                                endpos = i;
                                break;
                            }
                            else if (byteCountEnd == AllLen)// 记下当前位置
                            {
                                endpos = i + 1;
                                break;
                            }
                        }
                        endpos = endpos - startpos;
                    }
                    else if (startIndex + len > byteLen)//截取字符超出总长
                    {
                        endpos = charLen - startpos;
                    }
                    if (endpos >= 0)
                    { result = str.Substring(startpos, endpos); }
                }
                return result;
            }
    }
    View Code

    调用:

    //=》特殊处理 只读取20位长度的User数据
                    if (System.Text.Encoding.Default.GetBytes(user).Length > 20)//Saitor
                    {
                        user = user.CutByteString(20);
                    }
    View Code

    六、使用记秒表检查程序运行时间

    如果你担忧某些代码非常耗费时间,可以用StopWatch来检查这段代码消耗的时间,如下面的代码所示
    
    System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
    timer.Start();
    Decimal total = 0;
    int limit = 1000000;
    for (int i = 0; i < limit; ++i)
    {
          total = total + (Decimal)Math.Sqrt(i);
    }
    timer.Stop();
    Console.WriteLine(“Sum of sqrts: {0}”,total);
    Console.WriteLine(“Elapsed milliseconds: {0}”,
    timer.ElapsedMilliseconds);
    Console.WriteLine(“Elapsed time: {0}”, timer.Elapsed);
     
    现在已经有专门的工具来检测程序的运行时间,可以细化到每个方法,比如dotNetPerformance软件。
    
    以上面的代码为例子,您需要直接修改源代码,如果是用来测试程序,则有些不方便。请参考下面的例子。
    
    class AutoStopwatch : System.Diagnostics.Stopwatch, IDisposable
    {
       public AutoStopwatch()
       { 
           Start(); //base.Start();
       }
       public void Dispose()
       {
           Stop();//base.Stop();
           Console.WriteLine(“Elapsed: {0}”, this.Elapsed);
       }
    }
    借助于using语法,像下面的代码所示,可以检查一段代码的运行时间,并打印在控制台上。
    
    using (new AutoStopwatch())
    {
        Decimal total2 = 0;
        int limit2 = 1000000;
        for (int i = 0; i < limit2; ++i)
        {
           total2 = total2 + (Decimal)Math.Sqrt(i);
        }
    }
    View Code

    七、使用等待光标

    当程序正在后台运行保存或是册除操作时,应当将光标状态修改为忙碌。可使用下面的技巧。
    
    class AutoWaitCursor : IDisposable
    {
    private Control _target;
    private Cursor _prevCursor = Cursors.Default;
    public AutoWaitCursor(Control control)
    {
       if (control == null)
       {
         throw new ArgumentNullException(“control”);
       }
       _target = control;
       _prevCursor = _target.Cursor;
       _target.Cursor = Cursors.WaitCursor;
    }
    public void Dispose()
    {
       _target.Cursor = _prevCursor;
    }
    }
     
    用法如下所示,这个写法,是为了预料到程序可能会抛出异常
    
    using (new AutoWaitCursor(this))
    {
    ...
    throw new Exception();
    }
    如代码所示,即使抛出异常,光标也可以恢复到之间的状态。
    View Code
  • 相关阅读:
    如何巧妙着运用「位运算」来解决问题?
    一文读懂一台计算机是如何把数据发送给另一台计算机的
    Java集合与泛型中的几个陷阱,你掉进了几个?
    【链表问题】打卡10:将搜索二叉树转换成双向链表
    【链表问题】打卡9:将单链表的每K个节点之间逆序
    【链表问题】打卡8:复制含有随机指针节点的链表
    单例模式中的volatile关键字
    链表回文判断(基于链表反转)—Java实现
    设计模式之单例模式
    Spring的IoC与AOP的理解
  • 原文地址:https://www.cnblogs.com/51net/p/4010660.html
Copyright © 2020-2023  润新知