zoukankan      html  css  js  c++  java
  • c# string 扩展方法

    场景:只显示一字符串的前50个字符,多余的用“...”省略号替代

    如果不用扩展方法当然也可以实现,写一个静态方法,如下:

     1 public class StringUtil
     2     {
     3         /// <summary>
     4         /// 截取字符串
     5         /// </summary>
     6         /// <param name="str">要截取的字符串</param>
     7         /// <param name="length">截取长度</param>
     8         /// <returns></returns>
     9         public static string CutString(string str, int length)
    10         {
    11             if (!string.IsNullOrEmpty(str))
    12             {
    13                 if (str.Length <= length)
    14                 {
    15                     return str;
    16                 }
    17                 else
    18                 {
    19                     return str.Substring(0, length) + "...";
    20                 }
    21             }
    22             else
    23             {
    24                 return "";
    25             }
    26         }
    27 }
    28 
    29 不用扩展方法

    调用:

    string result=StringUtil.CutString(str,50);

    使用扩展方法:

    使用扩展方法要注意两个点:1)扩展方法必须定义在静态类中,2)使用this关键字

     1 public static class StringExtension
     2     {
     3         /// <summary>
     4         /// 截取字符串,多余部分用"..."代替
     5         /// </summary>
     6         /// <param name="str">源字符串</param>
     7         /// <param name="length">截取长度</param>
     8         /// <returns></returns>
     9         public static string CutString(this string str, int length)
    10         {
    11             if (!string.IsNullOrEmpty(str))
    12             {
    13                 if (str.Length <= length)
    14                 {
    15                     return str;
    16                 }
    17                 else
    18                 {
    19                     return str.Substring(0, length) + "...";
    20                 }
    21             }
    22             else
    23             {
    24                 return "";
    25             }
    26         }
    27 }
    28 
    29 扩展方法

    调用:

    string result=str.CutString(50);

    这样是不是方便一些,代码简洁一些,就像你去调用ToString(),Substring()等系统定义的方法一样。

  • 相关阅读:
    2020.05.02【NOIP普及组】模拟赛C组31总结
    【提高组NOIP2008】传纸条 题解
    【NOIP2006PJ】Jam的计数法(count)题解
    话说placeholder
    css垂直居中
    fixed和absolute的区别
    链接的属性href=“?” ?该些什么及优缺点
    论ul、ol和dl的区别
    笔记本插拔电源黑屏一下
    CSS 样式书写规范
  • 原文地址:https://www.cnblogs.com/amylis_chen/p/14419320.html
Copyright © 2011-2022 走看看