c# - 投然后检查还是检查然后投?

标签 c# casting

<分区>

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

哪种方法被认为是最佳实践?

先投?

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;
    }
}

还是先check,再cast?

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;
    }
}

你能找到其他方法吗?

最佳答案

如果对象可能是也可能不是您想要的类型,那么 as 运算符(您的第一种方法)在两个方面更好:

  • 可读性和易维护性:您只需指定一次类型
  • 表演:你只表演了一次,而不是两次。 (小知识:当您使用 is 关键字时,C# 编译器在内部将其翻译为 as,即 coke is Cola 等同于 (可乐作为可乐)!= null)

如果对象应该始终是请求的类型,那么只需执行 (Coke)cola 并在不是这种情况时让它抛出异常。

关于c# - 投然后检查还是检查然后投?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2550625/

相关文章:

Javascript 提示保存到 C# 中的变量,单击相同的按钮

c# - 按钮未以编程方式触发 ASP.NET 控件上的事件

c# - 有什么方法可以在不创建文件的情况下设置长 url 字符串吗?

c# - 应用栏窗口从停靠位置弹出,然后移动到停靠位置

sql - 在 SQL 中使用强制转换和多列选择

c# - .NET 自定义控件 (ToolStripControlHost) 对设计人员造成严重破坏

c - C中链表声明的区别

c++ - static_cast 抛出错误,但 C 风格的转换有效

swift - CLLocationCoordinate2D 不符合预期的字典值类型 'AnyObject'