不能忽略c#中的using和as操作符的用处
时间:2024-03-23 08:08:41
是不是很多人不用c#中的using和as操作符?甚至不知道?
其实这2个操作符在小处非常有用。
1、using
按照msdn的解释
using 语句定义一个范围,在此范围的末尾将处理对象。
举例:
class TestUsing:IDisposable
{
public void Dispose()
{
Console.WriteLine("Dispose");
}
public void Method()
{
Console.WriteLine("Do a method");
}
}
调用这个类:
using(TestUsing tu=new TestUsing())
{
tu.Method();
}
可以看到先后输出了Do a method和Dispose。
备注:实例化的对象必须实现 System.IDisposable 接口
2、as
msdn这么说:
as 运算符用于执行可兼容类型之间的转换。
as 运算符类似于类型转换,所不同的是,当转换失败时,as 运算符将产生空,而不是引发异常。在形式上,这种形式的表达式:
expression as type
等效于:
expression is type ? (type)expression : (type)null
只是 expression 只被计算一次。
请注意,as 运算符只执行引用转换和装箱转换。as 运算符无法执行其他转换,如用户定义的转换,这类转换应使用 cast 表达式来代替其执行。
举例:
object [] arr=new object[2];
arr[0]=123;
arr[1]="test";
foreach(object o in arr)
{
string s=(string)o;
Console.WriteLine(s);
}
这样的代码在转换类型失败的时候引发异常,代码修改成:
object [] arr=new object[2];
arr[0]=123;
arr[1]="test";
for(int i=0;i<arr.Length;i++)
{
string s=arr[i] as string;
if(s!=null)Console.WriteLine(i+":"+s);
} 可以看到输出了1:test,虽然arr[0]处转换失败但是没有引发异常而是返回了null
备注:as必须和引用类型一起使用(int等值类型不能使用)
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
MySQL触发器trigger的使用
![](https://img.aspxhome.com/file/2023/1/114031_0s.png)
python绘制直线的方法
![](https://img.aspxhome.com/file/2023/5/93565_0s.jpg)
python编码问题汇总
![](https://img.aspxhome.com/file/2023/5/63185_0s.png)
分享8点超级有用的Python编程建议(推荐)
![](https://img.aspxhome.com/file/2023/2/66432_0s.png)
原生js编写autoComplete插件
php和asp利用Shell.Application来执行程序的代码
python编程开发之textwrap文本样式处理技巧
我的快递一个月没动静于是赶紧上线python快递查询系统
![](https://img.aspxhome.com/file/2023/8/87698_0s.png)
目标检测mAP的概念及公式详解
![](https://img.aspxhome.com/file/2023/3/132433_0s.png)
mysql多表连接查询实例讲解
python实现提取str字符串/json中多级目录下的某个值
![](https://img.aspxhome.com/file/2023/7/90707_0s.jpg)
python数据分析工具之 matplotlib详解
![](https://img.aspxhome.com/file/2023/0/107040_0s.jpg)
使用百度云加速后网站打开速度慢、广告不显示的解决方法
![](https://img.aspxhome.com/file/2023/2/112092_0s.png)
详解Python中Pyyaml模块的使用
![](https://img.aspxhome.com/file/2023/0/99150_0s.png)
Python 利用pydub库操作音频文件的方法
制定设计的原则
![](https://img.aspxhome.com/file/UploadPic/20111/10/01-21s.jpg)
Asp中Server.ScriptTimeOut脚本超时属性需要注意的一点
line-height 属性的继承问题
Mootools 1.2教程(18)——Class 类(第一部分)
python处理json文件的四个常用函数
![](https://img.aspxhome.com/file/2023/5/128345_0s.png)