本文整理汇总了C#中System.Convert类的典型用法代码示例。如果您正苦于以下问题:C# Convert类的具体用法?C# Convert怎么用?C# Convert使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Convert类属于System命名空间,在下文中一共展示了Convert类的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: catch
double dNumber = 23.15;
try {
// Returns 23
int iNumber = System.Convert.ToInt32(dNumber);
}
catch (System.OverflowException) {
System.Console.WriteLine(
"Overflow in double to int conversion.");
}
// Returns True
bool bNumber = System.Convert.ToBoolean(dNumber);
// Returns "23.15"
string strNumber = System.Convert.ToString(dNumber);
try {
// Returns '2'
char chrNumber = System.Convert.ToChar(strNumber[0]);
}
catch (System.ArgumentNullException) {
System.Console.WriteLine("String is null");
}
catch (System.FormatException) {
System.Console.WriteLine("String length is greater than 1.");
}
// System.Console.ReadLine() returns a string and it
// must be converted.
int newInteger = 0;
try {
System.Console.WriteLine("Enter an integer:");
newInteger = System.Convert.ToInt32(
System.Console.ReadLine());
}
catch (System.ArgumentNullException) {
System.Console.WriteLine("String is null.");
}
catch (System.FormatException) {
System.Console.WriteLine("String does not consist of an " +
"optional sign followed by a series of digits.");
}
catch (System.OverflowException) {
System.Console.WriteLine(
"Overflow in string to int conversion.");
}
System.Console.WriteLine("Your integer as a double is {0}",
System.Convert.ToDouble(newInteger));
示例2: Main
//引入命名空间
using System;
public class Example
{
public static void Main()
{
int[] baseValues = { 2, 8, 10, 16 };
short value = Int16.MaxValue;
foreach (var baseValue in baseValues) {
String s = Convert.ToString(value, baseValue);
short value2 = Convert.ToInt16(s, baseValue);
Console.WriteLine("{0} --> {1} (base {2}) --> {3}",
value, s, baseValue, value2);
}
}
}
输出:
32767 --> 111111111111111 (base 2) --> 32767 32767 --> 77777 (base 8) --> 32767 32767 --> 32767 (base 10) --> 32767 32767 --> 7fff (base 16) --> 32767