C#中as和is关键字
一. as 运算符用于在兼容的引用类型之间执行某些类型的转换。例如:
static void Main(string[] args)
{
object[] obj = new object[3];
obj[0] = new class1();
obj[1] = "hello";
obj[2] = 10;
for (int i = 0; i < obj.Length; i++)
{
string s = obj[i] as string;
if (s != null)
{
Console.WriteLine(s);
}
else
{
Console.WriteLine("not a string");
}
}
Console.ReadLine();
}
{
object[] obj = new object[3];
obj[0] = new class1();
obj[1] = "hello";
obj[2] = 10;
for (int i = 0; i < obj.Length; i++)
{
string s = obj[i] as string;
if (s != null)
{
Console.WriteLine(s);
}
else
{
Console.WriteLine("not a string");
}
}
Console.ReadLine();
}
结果:
not a string
hello
not a string
class Base
{
public override string ToString()
{
return "Base";
}
}
class Derived : Base
{ }
class Program
{
static void Main()
{
Derived d = new Derived();
Base b = d as Base;
if (b != null)
{
Console.WriteLine(b.ToString());
}
}
}
{
public override string ToString()
{
return "Base";
}
}
class Derived : Base
{ }
class Program
{
static void Main()
{
Derived d = new Derived();
Base b = d as Base;
if (b != null)
{
Console.WriteLine(b.ToString());
}
}
}
对于继承类,允许把子类转换成父类,但是不可以把父类转换成子类,不同类之间,值类型不可转换。
二.is检查对象是否与给定类型兼容。
例如,下面的代码可以确定对象是否为 MyObject 类型的一个实例,或者对象是否为从 MyObject 派生的一个类型:
if (obj is MyObject) { }
如果所提供的表达式非空,并且所提供的对象可以强制转换为所提供的类型而不会导致引发异常,则 is 表达式的计算结果将是 true。
如果已知表达式将始终是 true 或始终是 false,则 is 关键字将导致编译时警告,但是,通常在运行时才计算类型兼容性。
不能重载 is 运算符。
请注意,is 运算符只考虑引用转换、装箱转换和取消装箱转换。不考虑其他转换,如用户定义的转换。
在 is 运算符的左侧不允许使用匿名方法。lambda 表达式属于例外。
class MyQuickSort
{
static void Main(string[] args)
{
class2 c2 = new class2();
if (c2 is class1)
{
Console.WriteLine("Yes");
}
else
{
Console.WriteLine("No");
}
Console.ReadLine();
}
}
class class1
{
public override string ToString()
{
return "";
}
}
class class2:class1
{
}
{
static void Main(string[] args)
{
class2 c2 = new class2();
if (c2 is class1)
{
Console.WriteLine("Yes");
}
else
{
Console.WriteLine("No");
}
Console.ReadLine();
}
}
class class1
{
public override string ToString()
{
return "";
}
}
class class2:class1
{
}
结果:Yes
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述