[英]Is there any equivalent to JavaScript's decodeURIComponent() in C#?
[英]Logical operator && in JavaScript and it's C# equivalent
在 JavaScritp 中,運算符 && 可用於調用這樣的函數
possibleNull && possibleNull.do()
這僅執行 possibleNull object 不是 null 的 possibleNull object 的 do() 方法。 這個可以處理嗎? 操作員。 但是我找不到 C# 替代品
let foo = _fooProvider.GetFoo();
return foo && processFoo(foo);
在 JS 的 "left && right" 表達式中,當左側變量被評估為 "true" 時(一般不是 null -> JS 中有更多情況),返回(或執行)右側變量。
我知道 C# 替代 || 工作原理幾乎相同的 JS 運算符(?? 運算符)。 &&也有對應的嗎?
編輯:我知道當兩個操作數都是布爾值時 && 可以短路。 但是,在 JS 中,您可以讓右側返回 bool 以外的其他內容。 JS 中的左側確實被解釋器自動轉換為布爾值,而右側只是被評估並返回。
我想實現類似
public Foo Do(Foo arg)
...
var foo = _fooProvider.GetFoo();
return foo != null && Do(foo);
不使用 if-else 或三元運算符。
您真正要問的是邏輯運算符“短路”,如果多條件測試中的第一個條件失敗,則語句處理將停止。
& Logical AND
&& Logical AND with short-circuiting
| Logical OR
|| Logical OR with short-circuiting
如果你想要一個面向對象的解決方案來解決你的問題。 為什么不實現 null 模式?
我不知道 Foo 在您的情況下是否有接口,或者是否可以合理實現。
但是,與其用 null 檢查亂扔代碼,不如讓所有 null 行為四處游盪。 (比如如果 object 是 null 記錄一些東西)
做類似的事情
public interface IFoo { void Do(); }
public class Foo : IFoo { void Do() { /* all that stuff you wanna do */ } }
public class NullFoo : IFoo { void Do { /*log that do cannot be called on nullFoo because Foo with Code X could not be found */ } }
Foo 可能來自倉庫或工廠,當您看到它無法實例化時。 與其讓客戶端檢查 null,不如返回 NullFoo,讓它調用 Do 什么都不做或記錄它找不到,然后 go 就在它的一天:)
希望這可以幫助!
C# 中的 && 運算符的工作方式與 JavaScript 中的一樣,但僅適用於bool
操作數。 JavaScript 中可以有任何類型的操作數。
JavaScript 使用類型強制 - 它將 boolean 值(真/假)分配給非布爾變量。
0 -> false
non-0 number -> true
[] -> false
non-empty array -> true
undefined, null -> false
{} -> true
JS 中的x && y
是這樣工作的:如果 x 強制為 false,則返回 x。 如果 x 強制為真,則返回 y。
C# 的工作方式相同,只是僅使用 bool 操作數。 如果 x 為假,則返回 x (假)。 如果 x 為真且 y 為假,則返回 y(假)。 如果 x 為真且 y 為真,則返回 y (true)。
現在這對於編寫像 JS 這樣的短代碼並不是很有用。 可能你能做的最好的事情是if (foo != null) processFoo(foo)
或三元foo == null? getNewFoo(): processFoo(foo)
foo == null? getNewFoo(): processFoo(foo)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.