




















1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Text;
5
6
namespace TypeCast
7
{
8
internal class Employee
9
{
10
11
}
12
internal class Manager : Employee
13
{
14
15
}
16
class Program
17
{
18
static void Main(string[] args)
19
{
20
Manager m = new Manager();
21
Employee e = m as Employee;
22
if (e != null)
23
{
24
Console.WriteLine(e.GetType().ToString());
25
}
26
27
PromoteEmployee(m);
28
//the cast above no fails:Cause Manager is derived from Employee
29
30
31
Object o = new object();
32
Employee e1 = o as Employee;
33
if (e1 != null)
34
{
35
Console.WriteLine(e.GetType().ToString());
36
}
37
//the cast above fails:no exception is thrown,but e1 is set to null
38
39
PromoteEmployee(o);
40
//the cast above fails: exception is thrown
41
}
42
43
public static void PromoteEmployee(Object o)
44
{
45
Employee e = (Employee)o;
46
Console.WriteLine(e.GetType().ToString());
47
}
48
}
49
注意:用As 类型转换操作不会抛出异常.
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。