📌  相关文章
📜  C#| Convert.ToString(String,IFormatProvider)方法

📅  最后修改于: 2021-05-29 23:04:25             🧑  作者: Mango

此方法用于返回指定的字符串实例,并且不执行任何实际转换。

句法:

public static string ToString (String, IFormatProvider);

参数:

  • value :它是要返回的字符串。
  • provider提供者,它提供特定于区域性的格式信息。该参数被忽略。

返回值:此方法返回的值保持不变。

下面的程序说明了Convert.ToString(String,IFormatProvider)方法的用法:

范例1:

// C# program to demonstrate the
// Convert.ToString() Method
using System;
using System.Globalization;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        try {
  
            // creating object of CultureInfo
            CultureInfo cultures = 
              new CultureInfo("en-US");
  
            // declaring and intializing String array
            string[] values = {"amar", "akbar",
                                    "anthony"};
  
            // calling get() Method
            Console.Write("Converted string value"
                  + " from a specified string: ");
  
            for (int j = 0; j < values.Length; j++) 
            {
                get(values[j], cultures);
            }
        }
  
        catch (FormatException e) 
        {
            Console.WriteLine("\n");
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
  
        catch (OverflowException e) 
        {
            Console.WriteLine("\n");
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
  
    // Defining get() method
    public static void get(string s,
               CultureInfo cultures)
    {
  
        // converting string to specified string
        string val = Convert.ToString(s, cultures);
  
        // display the converted string value
        Console.Write(" {0} ", val);
    }
}
输出:
Converted string value from a specified string:  amar  akbar  anthony

范例2:

// C# program to demonstrate the
// Convert.ToString() Method
using System;
using System.Globalization;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        // creating object of CultureInfo
        CultureInfo cultures = 
          new CultureInfo("en-US");
  
        // declaring and initializing a String array
        string value = "The Accidental Prime Minister";
  
        // calling get() Method
        Console.Write("Converted String: ");
  
        // converting string to specified string
        string val = Convert.ToString(value, cultures);
  
        // display the converted string value
        Console.Write("{0}", val);
    }
}
输出:
Converted String: The Accidental Prime Minister

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.convert.tostring?view=netframework-4.7.2#System_Convert_ToString_System_String_System_IFormatProvider_