开发者

Difference in casting in the following 2 methods [duplicate]

开发者 https://www.devze.com 2023-01-01 14:54 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: casting vs using the ‘as’ keyword in the CLR
This question already has answers here: Closed 12 years ago.

Possible Duplicate:

casting vs using the ‘as’ keyword in the CLR

hi,

ca开发者_如何学运维n somebody please tell me what is the difference between the following two statements, because both of them give me the same results. Also i want to know which is better.

Label lblSome = e.Item.FindControl("lblMyLable") as Label;

&&

Label lblSome = (Label)e.Item.FindControl("lblMyLable");

thank you so much.


as checks if it can cast it, if it can't, it sets lblSome to null. Normal casting, (Label), doesn't do that check for you, just gives you an InvalidCastException instead. However, as doesn't work with non-nullable structs.


if e.Item.FindControl("lblMyLable") returns an object that is not Label (Label)e.Item.FindControl("lblMyLable") will result in InvalidCastException. while e.Item.FindControl("lblMyLable") as Label will result in null being assigned to lblSome.

0

精彩评论

暂无评论...
验证码 换一张
取 消