直接铸造vs'as'运算符? [英] Direct casting vs 'as' operator?

查看:115
本文介绍了直接铸造vs'as'运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

  void Handler(object o,EventArgs e)
{
//我发誓o是一个字符串
string s =(string)o; // 1
// - OR-
string s = o as string; // 2
// -OR-
string s = o.ToString(); // 3
}

这三种类型的铸造有什么区别

解决方案

<$ p $(第三个不是一个铸件,但你得到的意图...) p> string s =(string)o; // 1

抛出 InvalidCastException 如果 o 不是字符串。否则,将 o 分配给 s ,即使 o null

  string s = o as string; // 2 

指派 null s 如果 o 不是字符串 c> o 是 null 。因此,您不能将其用于值类型(在这种情况下,运算符永远不会返回 null )。否则,将 o 分配给 s

  string s = o.ToString(); // 3 

导致 NullReferenceException 如果 o null 。分配任何 o.ToString()返回 s ,无论什么类型 code>是。






对于大多数转化使用1,这很简单直接。我倾向于几乎从不使用2,因为如果东西不是正确的类型,我通常期望发生异常。我只看到一个需要这个返回null类型的功能与设计非常糟糕的库使用错误代码(例如返回null =错误,而不是使用异常)。



3不是一个强制转换,只是一个方法调用。当您需要非字符串对象的字符串表示形式时使用它。


Consider the following code:

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, 3rd one is not a casting, but you get the intent... ), and which one should be preferred?

解决方案

string s = (string)o; // 1

Throws InvalidCastException if o is not a string. Otherwise, assigns o to s, even if o is null.

string s = o as string; // 2

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

Causes a NullReferenceException if o is null. Assigns whatever o.ToString() returns to s, no matter what type o is.


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 is not a cast and is just a method invocation. Use it for when you need the string representation of a non-string object.

这篇关于直接铸造vs'as'运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆