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 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语