Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

c# - 直接铸造与“ as”运算符?(Direct casting vs 'as' operator?)

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, the 3rd one is not a casting, but you get the intent).

(三种类型的转换之间有什么区别(好吧,第三个类型不是转换,但是您有意图)。)

Which one should be preferred?

(应该首选哪一个?)

  ask by nullDev translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
string s = (string)o; // 1

Throws InvalidCastException if o is not a string .

(如果o不是string则抛出InvalidCastException 。)

Otherwise, assigns o to s , even if o is null .

(否则,将o分配给s ,即使onull 。)

string s = o as string; // 2

Assigns null to s if o is not a string or if o is null .

(分配nulls ,如果o是不是一个string ,或者onull 。)

For this reason, you cannot use it with value types (the operator could never return null in that case).

(因此,您不能将其与值类型一起使用(在这种情况下,运算符永远不会返回null )。)

Otherwise, assigns o to s .

(否则,将o分配给s 。)

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

Causes a NullReferenceException if o is null .

(如果onull则导致NullReferenceException 。)

Assigns whatever o.ToString() returns to s , no matter what type o is.

(将o.ToString()返回的值o.ToString() s ,无论o是什么类型。)


Use 1 for most conversions - it's simple and straightforward.

(大多数转换使用1-简单明了。)

I tend to almost never use 2 since if something is not the right type, I usually expect an exception to occur.

(我倾向于几乎从不使用2,因为如果某些类型不正确,我通常希望发生异常。)

I have only seen a need for this return-null type of functionality with badly designed libraries which use error codes (eg return null = error, instead of using exceptions).

(我只看到这种返回null类型的功能需要使用错误代码(例如,返回null =错误,而不是使用异常)的错误设计的库。)

3 is not a cast and is just a method invocation.

(3不是强制转换,而只是方法调用。)

Use it for when you need the string representation of a non-string object.

(在需要非字符串对象的字符串表示形式时使用它。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...