投再检查或检查再投? [英] Cast then check or check then cast?

查看:125
本文介绍了投再检查或检查再投?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:结果
VS铸造用'为'在CLR


关键字



哪种方法被视为最佳做法?



第一投?

 公共字符串描述(ICola可乐)
{
VAR焦=可乐是可口可乐;
如果(焦炭!​​= NULL)
{
字符串结果;
//一些独特的可口可乐只在这里的代码。
返回结果;
}
VAR百事可乐=可乐百事可乐;
如果(百事可乐!= NULL)
{
字符串结果;
//一些独特的百事可乐这里只代码。
返回结果;
}
}



或者我应该先检查,后投?

 公共字符串描述(ICola可乐)
{
如果(可乐是可口可乐)
{
VAR焦=(可口可乐)可乐;
字符串结果;
//一些独特的可口可乐只在这里的代码。
返回结果;
}
如果(可乐百事)
{
VAR百事可乐=(百事可乐)可乐;
字符串结果;
//一些独特的百事可乐这里只代码。
返回结果;
}
}

您可以看到任何其他方式做到这一点?


解决方案

如果该对象可能是也可能不是你想要,那么该类型的操作符(你的第一法)两种方式更好:



<维护UL>
  • 可读性和易用性:你只指定一次类型

  • 性能:你只执行转换一次,而不是两次。 (花絮:当您使用关键字,C#编译器在内部将其转换为,即焦炭可乐等同于(焦炭可乐)!= NULL



  • 如果该对象应始终请求的类型,那么就去做(可乐)可乐,让它抛出一个异常,如果这不是的情况。


    Possible Duplicate:
    Casting vs using the ‘as’ keyword in the CLR

    Which method is regarded as best practice?

    Cast first?

    public string Describe(ICola cola)
    {
        var coke = cola as CocaCola;
        if (coke != null)
        {
            string result;
            // some unique coca-cola only code here.
            return result;
        }
        var pepsi = cola as Pepsi;
        if (pepsi != null)
        {
            string result;
            // some unique pepsi only code here.
            return result;
        }
    }
    

    Or should I check first, cast later?

    public string Describe(ICola cola)
    {
        if (cola is CocaCola)
        {
            var coke = (CocaCola) cola;
            string result;
            // some unique coca-cola only code here.
            return result;
        }
        if (cola is Pepsi)
        {
            var pepsi = (Pepsi) cola;
            string result;
            // some unique pepsi only code here.
            return result;
        }
    }
    

    Can you see any other way to do this?

    解决方案

    If the object may or may not be of the type you want then the as operator (your first method) is better in two ways:

    • Readability and ease of maintenance: you are only specifying the type once
    • Performance: you are only performing the cast once, instead of twice. (Trivia: when you use the is keyword, the C# compiler internally translates it to as, ie. coke is Cola is equivalent to (coke as Cola) != null)

    If the object should always be of the requested type then just do (Coke)cola and let it throw an exception if that's not the case.

    这篇关于投再检查或检查再投?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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