它的代码是更好的:使用" AS"或QUOT;是"? [英] Which code is better: using "as" or "is"?

查看:169
本文介绍了它的代码是更好的:使用" AS"或QUOT;是"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:结果
VS铸造用'为'在CLR 结果
关键字的 C#:“是”的VS&ld​​quo;如”的






此代码:

 如果(sheet.Models.Data是GroupDataModel)
{
GroupDataModel GDM =(GroupDataModel)sheet.Models.Data;

和下面的代码:

  GroupDataModel GDM = sheet.Models.Data为GroupDataModel; 
如果(GDM!= NULL)
{



你推荐任何的两种风格上面比其他的?


解决方案

我认为它能够更好地去作为,因为它转换,以及你可以做检查很容易..second一个是好



更多关于这一点:的 <对象和角色STRONG>显性和隐性铸造'是'和'为'显式转换


  • 作为运营商做转换构成一个类型之间p>

    差异为另一种类型,并返回NULL,如果converstion
    失败。有没有必要再转换如果它的敞篷车。


  • 是运营商检查的天气里,对象是另一种类型的转换与否,如果没有返回false。因此,如果需要它转换为对象转换为基本类型。



Possible Duplicate:
Casting vs using the 'as' keyword in the CLR
C#: “is” vs “as”

This code:

    if (sheet.Models.Data is GroupDataModel)
    {
        GroupDataModel gdm = (GroupDataModel)sheet.Models.Data;

and this code:

    GroupDataModel gdm = sheet.Models.Data as GroupDataModel;
    if (gdm != null)
    {

Do you recommend any of the two styles above over the other one?

解决方案

I think its better to go for as because it convert as well as you can do check easily ..second one is good

More about this: Explicit and Implicit Casting of object and Role of 'is' and 'as' keyword in Explicit casting

Difference between as and is

  • as operator do conversion form one type to another type and return Null if converstion fails. There is no need to conversion again if its convertible.

  • is operator checks weather one object is convertible in another type or not and return false if not. So need to convert object to base type if it convertible.

这篇关于它的代码是更好的:使用&QUOT; AS&QUOT;或QUOT;是&QUOT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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