今天我遇到了一个场景,同时在我的应用程序中实现了搜索功能,让我感到困惑.看看这个片段:
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.希望这些酒吧有助于更清楚地向您展示差异.