输入Cast Operator Precedence

MDi*_*sel 3 c#

今天我遇到了一个场景,同时在我的应用程序中实现了搜索功能,让我感到困惑.看看这个片段:

public string GetFirstProductName(SortedList<string, object> itemsList) {
    for (int i = 0; i < itemsList.Values.Count; i++) {
        if (itemsList.Values[i] is Product)
           // Doesn't Compile:
           // return (Product)itemsList.Values[i].ProductName;

           // Does compile. Precedence for the "." higher than the cast?
           return ((Product)itemsList.Values[i]).ProductName;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

那么,演员的优先权是什么?是演员吗?as关键字怎么样- 是运营商,它的优先级是什么?

Sim*_*ead 12

它非常简单.

如果你没有将转换包装在括号中..你正在转换整个表达式:

return (Product)itemsList.Values[i].ProductName;
//              |______________________________|
Run Code Online (Sandbox Code Playgroud)

你基本上是string一个人Product.鉴于:

return ((Product)itemsList.Values[i]).ProductName;
//     |____________________________|
Run Code Online (Sandbox Code Playgroud)

仅转换该部分,允许.访问a的属性Product.希望这些酒吧有助于更清楚地向您展示差异.

  • “当您不将转换括在括号中时.. 您正在转换整个表达式”是真的 *对于这个特定示例*,因为“。” 是主运算符,具有最高优先级,而 (T)x 运算符是一元运算符,并且是第二高的。不一定适用于所有表达式! (2认同)