Direct casting vs #39;as#39; operator?(直接铸造与as运营商?)
问题描述
考虑以下代码:
void Handler(object o, EventArgs e)
{
// I swear o is a string
string s = (string)o; // 1
//-OR-
string s = o as string; // 2
// -OR-
string s = o.ToString(); // 3
}
这三种类型的施法有什么区别(好吧,第三种不是施法,但你明白了).应该首选哪一个?
What is the difference between the three types of casting (okay, the 3rd one is not a casting, but you get the intent). Which one should be preferred?
推荐答案
string s = (string)o; // 1
如果 o 是,则抛出 InvalidCastException不是字符串.否则,将 o 分配给 s,即使 o 为 null.
Throws InvalidCastException if o is not a string. Otherwise, assigns o to s, even if o is null.
string s = o as string; // 2
如果 o 不是 string 或者如果 o 则将 null 分配给 s> 是 null.因此,您不能将它与值类型一起使用(在这种情况下,运算符永远不会返回 null).否则,将 o 分配给 s.
Assigns null to s if o is not a string or if o is null. For this reason, you cannot use it with value types (the operator could never return null in that case). Otherwise, assigns o to s.
string s = o.ToString(); // 3
如果 o 会导致 NullReferenceException是 null.将任何 o.ToString() 返回的内容分配给 s,无论 o 是什么类型.
Causes a NullReferenceException if o is null. Assigns whatever o.ToString() returns to s, no matter what type o is.
对大多数转换使用 1 - 它简单明了.我几乎从不使用 2 ,因为如果某些类型不正确,我通常希望会发生异常.我只看到使用错误代码(例如返回 null = 错误,而不是使用异常)的糟糕设计的库需要这种返回 null 类型的功能.
Use 1 for most conversions - it's simple and straightforward. I tend to almost never use 2 since if something is not the right type, I usually expect an exception to occur. I have only seen a need for this return-null type of functionality with badly designed libraries which use error codes (e.g. return null = error, instead of using exceptions).
3 不是强制转换,只是一个方法调用.当您需要非字符串对象的字符串表示时使用它.
3 is not a cast and is just a method invocation. Use it for when you need the string representation of a non-string object.
这篇关于直接铸造与'as'运营商?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:直接铸造与'as'运营商?
基础教程推荐
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 如果条件可以为空 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 将数据集转换为列表 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
