C#中“ is”关键字的用途是什么?
的“是”关键字用于检查是否一个对象可以被浇铸到一个特定的类型。操作的返回类型为布尔值。
示例
using System;
namespace DemoApplication{
class Program{
static void Main(){
Employee emp = new PermanentEmployee{
ID = 1,
Name = "Martin"
};
//返回true,因为派生类型可以转换为基本类型。
if (emp is Employee){
Console.WriteLine(emp.Name + " is Employee");
}
else{
Console.WriteLine(emp.Name + " is not Employee");
}
//返回true,因为实际对象的类型为PermanentEmployee。
if (emp is PermanentEmployee){
Console.WriteLine(emp.Name + " is PermanentEmployee");
}
else{
Console.WriteLine(emp.Name + " is not PermanentEmployee");
}
//返回false,因为PermanentEmployee对象无法转换为
//ContractEmployee。
if (emp is ContractEmployee){
Console.WriteLine(emp.Name + " is ContractEmployee");
}
else{
Console.WriteLine(emp.Name + " is not ContractEmployee");
}
}
}
class Employee{
public int ID { get; set; }
public string Name { get; set; }
}
class PermanentEmployee : Employee{
public int AnnualSalary { get; set; }
}
class ContractEmployee : Employee{
public int HourlySalary { get; set; }
}
}热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿