Int16.ToString方法用于将当前实例的数值转换为其等效的字符串表示形式。此方法的重载列表中有4种方法,如下所示:
- ToString(IFormatProvider)方法
- ToString(String,IFormatProvider)方法
- ToString()方法
- ToString(String)方法
在这里,我们将讨论最后两种方法。
ToString()方法
此方法用于将该实例的数值转换为其等效的字符串表示形式。
句法:
public override string ToString ();
返回值:此方法返回当前实例的值的字符串表示形式,如果值是负数,则由负号组成;数字序列的范围为0到9,无前导零。
例子:
// C# program to illustrate the
// Int16.ToString() Method
using System;
using System.Globalization;
class GFG {
// Main Method
public static void Main()
{
Console.WriteLine("The String values are: ");
// calling the method
result(Int16.MaxValue);
result(Int16.MinValue);
result(5006);
result(8459);
}
// result() method
public static void result(short p)
{
// using ToString() method
string str = p.ToString();
// Display the value
Console.WriteLine("The Corresponding String "+
"Value is: {0}", str);
}
}
输出:
The String values are:
The Corresponding String Value is: 32767
The Corresponding String Value is: -32768
The Corresponding String Value is: 5006
The Corresponding String Value is: 8459
ToString(String)方法
此方法用于使用指定的格式将此实例的数值转换为其等效的字符串表示形式。
句法:
public string ToString (string format);
参数:此方法采用数字格式的字符串。
返回值:该方法返回格式所指定的此实例的值的字符串表示形式。
例子:
// C# program to demonstrate the
// Int16.ToString(String) Method
using System;
class GFG {
// Main Method
public static void Main()
{
try {
// Declaring and initializing value
short s1 = 123;
// Declaring and initializing format
string format = "E2";
// using the method
string result = s1.ToString(format);
// Display the result
Console.WriteLine("The value of string is {0}", result);
}
catch (FormatException e) {
Console.WriteLine("Format is invalid.");
Console.Write("Exception Thrown: ");
Console.Write("{0}", e.GetType(), e.Message);
}
}
}
输出:
The value of string is 1.23E+002
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.int16.tostring?view=netframework-4.7.2