C# String扩展类 常用方法

在这里插入图片描述

  • 扩展作用

C#
中的扩展方法是一种能够向现有的类添加新方法的机制,而不需要修改原始类的代码。这使得您可以在不更改类定义的情况下,为已有的数据类型添加新功能或行为。

  • 扩展方法的作用包括但不限于:

    • 为现有类型添加新功能:您可以通过扩展方法为标准库或第三方库中的类添加新的方法,以满足特定的需求。

    • 提高代码的可读性:通过在相关的上下文中定义扩展方法,可以使代码更具可读性和语义性。

    • 避免子类化:有时,为了添加一些额外的功能,您可能会考虑创建一个子类。但是,使用扩展方法可以避免创建子类,从而保持代码的简洁性和可维护性。

   ///<summary>
   ///   Provides extension methods to the <see cref="string">System.string</see> object.
   /// </summary>
   public static class StringExtensions
   {
   
       /// <summary>
       ///     Checks if date with dateFormat is parse-able to System.DateTime format returns boolean value if true else false
       /// </summary>
       /// <param name="data">String date</param>
       /// <param name="dateFormat">date format example dd/MM/yyyy HH:mm:ss</param>
       /// <returns>boolean True False if is valid System.DateTime</returns>
       public static bool IsDateTime(this string data, string dateFormat)
       {
   
           // ReSharper disable once RedundantAssignment
           DateTime dateVal = default(DateTime);
           return DateTime.TryParseExact(data, dateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None,
               out dateVal);
       }

       /// <summary>
       ///     Converts the string representation of a number to its 32-bit signed integer equivalent
       /// </summary>
       /// <param name="value">string containing a number to convert</param>
       /// <returns>System.Int32</returns>
       /// <remarks>
       ///     The conversion fails if the string parameter is null, is not of the correct format, or represents a number
       ///     less than System.Int32.MinValue or greater than System.Int32.MaxValue
       /// </remarks>
       public static int ToInt32(this string value)
       {
   
           int number;
           Int32.TryParse(value, out number);
           return number;
       }

       /// <summary>
       ///     Converts the string representation of a number to its 64-bit signed integer equivalent
       /// </summary>
       /// <param name="value">string containing a number to convert</param>
       /// <returns>System.Int64</returns>
       /// <remarks>
       ///     The conversion fails if the string parameter is null, is not of the correct format, or represents a number
       ///     less than System.Int64.MinValue or greater than System.Int64.MaxValue
       /// </remarks>
       public static long ToInt64(this string value)
       {
   
           long number;
           Int64.TryParse(value, out number);
           return number;
       }

       /// <summary>
       ///     Converts the string representation of a number to its 16-bit signed integer equivalent
       /// </summary>
       /// <param name="value">string containing a number to convert</param>
       /// <returns>System.Int16</returns>
       /// <remarks>
       ///     The conversion fails if the string parameter is null, is not of the correct format, or represents a number
       ///     less than System.Int16.MinValue or greater than System.Int16.MaxValue
       /// </remarks>
       public static short ToInt16(this string value)
       {
   
           short number;
           Int16.TryParse(value, out number);
           return number;
       }

       /// <summary>
       ///     Converts the string representation of a number to its System.Decimal equivalent
       /// </summary>
       /// <param name="value">string containing a number to convert</param>
       /// <returns>System.Decimal</returns>
       /// <remarks>
       ///     The conversion fails if the s parameter is null, is not a number in a valid format, or represents a number
       ///     less than System.Decimal.MinValue or greater than System.Decimal.MaxValue
       /// </remarks>
       public static Decimal ToDecimal(this string value)
       {
   
           Decimal number;
           Decimal.TryParse(value, out number);
           return number;
       }

       /// <summary>
       ///     Converts string to its boolean equivalent
       /// </summary>
       /// <param name="value">string to convert</param>
       /// <returns>boolean equivalent</returns>
       /// <remarks>
       ///     <exception cref="ArgumentException">
       ///         thrown in the event no boolean equivalent found or an empty or whitespace
       ///         string is passed
       ///     </exception>
       /// </remarks>
       public static bool ToBoolean(this string value)
       {
   
           if (string.IsNullOrEmpty(value) || string.IsNullOrWhiteSpace(value))
           {
   
               throw new ArgumentException("value");
           }
           string val = value.ToLower().Trim();
           switch (val)
           {
   
               case "false":
                   return false;
               case "f":
                   return false;
               case "true":
                   return true;
               case "t":
                   return true;
               case "yes":
                   return true;
               case "no":
                   return false;
               case "y":
                   return true;
               case "n":
                   return false;
               default:
                   throw new ArgumentException("Invalid boolean");
           }
       }

       /// <summary>
       ///     Returns an enumerable collection of the specified type containing the substrings in this instance that are
       ///     delimited by elements of a specified Char array
       /// </summary>
       /// <param name="str">The string.</param>
       /// <param name="separator">
       ///     An array of Unicode characters that delimit the substrings in this instance, an empty array containing no
       ///     delimiters, or null.
       /// </param>
       /// <typeparam name="T">
       ///     The type of the element to return in the collection, this type must implement IConvertible.
       /// </typeparam>
       /// <returns>
       ///     An enumerable collection whose elements contain the substrings in this instance that are delimited by one or more
       ///     characters in separator.
       /// </returns>
       public static IEnumerable<T> SplitTo<T>(this string str, params char[] separator) where T : IConvertible
       {
   
           return str.Split(separator, StringSplitOptions.None).Select(s => (T)Convert.ChangeType(s, typeof(T)));
       }

       /// <summary>
       ///     Returns an enumerable collection of the specified type containing the substrings in this instance that are
       ///     delimited by elements of a specified Char array
       /// </summary>
       /// <param name="str">The string.</param>
       /// <param name="options">StringSplitOptions <see cref="StringSplitOptions" /></param>
       /// <param name="separator">
       ///     An array of Unicode characters that delimit the substrings in this instance, an empty array containing no
       ///     delimiters, or null.
       /// </param>
       /// <typeparam name="T">
       ///     The type of the element to return in the collection, this type must implement IConvertible.
       /// </typeparam>
       /// <returns>
       ///     An enumerable collection whose elements contain the substrings in this instance that are delimited by one or more
       ///     characters in separator.
       /// </returns>
       public static IEnumerable<T> SplitTo<T>(this string str, StringSplitOptions options, params char[] separator)
           where T : IConvertible
       {
   
           return str.Split(separator, options).Select(s => (T)Convert.ChangeType(s, typeof(T)));
       }

       /// <summary>
       ///     Converts string to its Enum type
       ///     Checks of string is a member of type T enum before converting
       ///     if fails returns default enum
       /// </summary>
       /// <typeparam name="T">generic type</typeparam>
       /// <param name="value"> The string representation of the enumeration name or underlying value to convert</param>
       /// <param name="defaultValue"></param>
       /// <returns>Enum object</returns>
       /// <remarks>
       ///     <exception cref="ArgumentException">
       ///         enumType is not an System.Enum.-or- value is either an empty string ("") or
       ///         only contains white space.-or- value is a name, but not one of the named constants defined for the enumeration
       ///     </exception>
       /// </remarks>
       public static T ToEnum<T>(this string value, T defaultValue = default(T)) where T : struct
       {
   
           if (!typeof(T).IsEnum)
           {
   
               throw new ArgumentException("Type T Must of type System.Enum");
           }

           T result;
           bool isParsed = Enum.TryParse(value, true, out result);
           return isParsed ? result : defaultValue;
       }

       /// <summary>
       ///     Replaces one or more format items in a specified string with the string representation of a specified object.
       /// </summary>
       /// <param name="value">A composite format string</param>
       /// <param name="arg0">An System.Object to format</param>
       /// <returns>A copy of format in which any format items are replaced by the string representation of arg0</returns>
       /// <exception cref="ArgumentNullException">format or args is null.</exception>
       /// <exception cref="System.FormatException">
       ///     format is invalid.-or- The index of a format item is less than zero, or
       ///     greater than or equal to the length of the args array.
       /// </exception>
       public static string Format(this string value, object arg0)
       {
   
           return string.Format(value, arg0);
       }

       /// <summary>
       ///     Replaces the format item in a specified string with the string representation of a corresponding object in a
       ///     specified array.
       /// </summary>
       /// <param name="value">A composite format string</param>
       /// <param name="args">An object array that contains zero or more objects to format</param>
       /// <returns>
       ///     A copy of format in which the format items have been replaced by the string representation of the
       ///     corresponding objects in args
       /// </returns>
       /// <exception cref="ArgumentNullException">format or args is null.</exception>
       /// <exception cref="System.FormatException">
       ///     format is invalid.-or- The index of a format item is less than zero, or
       ///     greater than or equal to the length of the args array.
       /// </exception>
       public static string Format(this string 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值