直接铸造VS'为'经营者? [英] Direct casting vs 'as' operator?

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

问题描述

考虑以下code:

 无效处理程序(对象o,EventArgs的发送)
{
   //我发誓o为一个字符串
   字符串s =(字符串)O; // 1
   //-要么-
   字符串s = O作为字符串; // 2
   // -要么-
   字符串s = o.ToString(); // 3
}

有什么三类铸造的区别(好吧,第三一个是不是铸造,但你的意图...),哪一个应该是preferred?


解决方案

 字符串s =(字符串)O; // 1

如果 0 是不是字符串。否则,受让人 0 取值,即使 0

 字符串s = O作为字符串; // 2

分配取值如果 0 不是一个字符串或者 0 。出于这个原因,你不能与值类型使用(运营商不可能在这种情况下返回)。否则,受让人 0 取值

 字符串s = o.ToString(); // 3

原因一<一href=\"https://msdn.microsoft.com/en-us/library/system.nullreferenceexception\">NullReferenceException如果 0 。无论分配 o.ToString()返回取值,不管是什么类型 0


使用1对大多数转换 - 这是简单明了。我倾向于几乎从来不使用2,因为如果事情是不正确的类型,我通常希望发生异常。我只看到需要的功能与使用错误codeS设计糟糕的图书馆这个返回空值类型(例如,返回NULL =错误,而不是使用异常)。

3不是一个演员和仅仅是一个方法调用。用它来当你需要重新串一个非字符串对象的presentation。

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'为'经营者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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