本文整理匯總了C#中System.InvalidCastException類的典型用法代碼示例。如果您正苦於以下問題:C# InvalidCastException類的具體用法?C# InvalidCastException怎麽用?C# InvalidCastException使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
InvalidCastException類屬於System命名空間,在下文中一共展示了InvalidCastException類的5個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: Main
//引入命名空間
using System;
public class Example
{
public static void Main()
{
bool flag = true;
try {
IConvertible conv = flag;
Char ch = conv.ToChar(null);
Console.WriteLine("Conversion succeeded.");
}
catch (InvalidCastException) {
Console.WriteLine("Cannot convert a Boolean to a Char.");
}
try {
Char ch = Convert.ToChar(flag);
Console.WriteLine("Conversion succeeded.");
}
catch (InvalidCastException) {
Console.WriteLine("Cannot convert a Boolean to a Char.");
}
}
}
輸出:
Cannot convert a Boolean to a Char. Cannot convert a Boolean to a Char.
示例2: Main
//引入命名空間
using System;
public class Person
{
String _name;
public String Name
{
get { return _name; }
set { _name = value; }
}
}
public class PersonWithId : Person
{
String _id;
public string Id
{
get { return _id; }
set { _id = value; }
}
}
public class Example
{
public static void Main()
{
Person p = new Person();
p.Name = "John";
try {
PersonWithId pid = (PersonWithId) p;
Console.WriteLine("Conversion succeeded.");
}
catch (InvalidCastException) {
Console.WriteLine("Conversion failed.");
}
PersonWithId pid1 = new PersonWithId();
pid1.Name = "John";
pid1.Id = "246";
Person p1 = pid1;
try {
PersonWithId pid1a = (PersonWithId) p1;
Console.WriteLine("Conversion succeeded.");
}
catch (InvalidCastException) {
Console.WriteLine("Conversion failed.");
}
Person p2 = null;
try {
PersonWithId pid2 = (PersonWithId) p2;
Console.WriteLine("Conversion succeeded.");
}
catch (InvalidCastException) {
Console.WriteLine("Conversion failed.");
}
}
}
輸出:
Conversion failed. Conversion succeeded. Conversion succeeded.
示例3: Main
//引入命名空間
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
var culture = CultureInfo.InvariantCulture;
IFormatProvider provider = culture;
DateTimeFormatInfo dt = (DateTimeFormatInfo) provider;
}
}
輸出:
Unhandled Exception: System.InvalidCastException: Unable to cast object of type //System.Globalization.CultureInfo// to type //System.Globalization.DateTimeFormatInfo//. at Example.Main()
示例4: Main
//引入命名空間
using System;
public class Example
{
public static void Main()
{
object value = 12;
// Cast throws an InvalidCastException exception.
string s = (string) value;
}
}
示例5: Main
//引入命名空間
using System;
public class Example
{
public static void Main()
{
object value = 12;
string s = value.ToString();
Console.WriteLine(s);
}
}
輸出:
12