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; }
}
}热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短