2017-10-16 142 views
2

运营商: “布尔++” 在C#

public void Main() 
{ 
    int i = 0; 
    Console.WriteLine($"I was {i++}, now I is {i}"); 
    bool b = true; 
    Console.WriteLine($"B was {b}, now B is {b}"); 
} 
//I was 0, now I is 1 
//B was True, now B is True 

是否有改变B值 “内联” 的可能性?

实际的需要:在在线剃刀

bool isActive = true; 
@foreach(var item in list) { 
    <li class="@(isActive-- ? "active": "")">... 
} 

生产

<li class="active">... 
<li class="">... 
<li class="">... 
<li class="">... 
<li class="">... 

解决方法的实际例子与integers

int isActive = 1; 
@foreach(var item in list) { 
    <li class="@(isActive-- > 0 ? "active": "")">... 
} 
+0

你是指像否定运算符还是?你可以总是有'if(b = DoSomething())' –

+0

而不是像否定运算符 – Serge

+0

你是什么意思的“改变它”内联? – Amy

回答

-1

您应该能够使用@( )表达语法:

<li class="@(isActive ? "active" : " ")">My link here</li> 
+0

我只需要第一个活动类,而不是其他的 – Serge

+0

你可以保持空白其他部分。它将工作 – lazydeveloper

+0

我需要isActive只从一次变为真。 – Serge

1

您可以直接应用赋值运算符。它返回指定值:

// b = !b both assigns false to b and returns assigned value 
Console.WriteLine($"B was {b}, now B is {b = !b}"); 
// B was True, now B is False 

为了您的Razor视图例如,您可以(AB)使用这样的:

bool active = true; 
Console.WriteLine($"B is {(active ? (active = false) ? "" :"active" : "")}"); 
Console.WriteLine($"B is {(active ? (active = false) ? "" : "active" : "")}"); 
Console.WriteLine($"B is {(active ? (active = false) ? "" : "active" : "")}"); 
// outputs B is active 
// B is 
// B is 

不,我建议这一点,但正如你所说的,它只是一个语言问题。

+0

如何在我的Razor样本中工作? @(isActive?changeIt) – Serge

+0

我发现一个解决方案(在更新OP)与整数...但与bools是更复杂:) – Serge

0

inlining在改变if-conditition变量的意义上是可能的。

var b = false; 
if((b = !b) == true) { 
    Console.WriteLine("Hi"); 
} 

本编译意愿打印Hi

这同样适用于你的剃须刀声明,或同时格式化字符串:

Console.WriteLine($"b was {b}, now b is {b = !b}"); 
// b was true, now b is false 

关于你提到的例子,这是不可能与一个ternary if声明。

我们可以使用一条语句将变量设置为false,并将其设置为而不是 print active

b ? (b = false) : ""; 

然后我们就可以嵌套另一个if声明打印活跃。因为b已经是false我们需要否定b。 else-路径中的空字符串将永远不会被达到,但需要满足编译器。

!(b = false) ? "active" : "never reached" 

组合这些后,我们得到:

b ? (!(b = false) ? "active" : "") : ""; 

这只会发出active的第一个项目。

var b = true; 
Console.WriteLine(b ? (!(b = false) ? "active" : "") : ""); // prints "active" 
Console.WriteLine(b ? (!(b = false) ? "active" : "") : ""); // prints "" 
Console.WriteLine(b ? (!(b = false) ? "active" : "") : ""); // prints "" 
+0

谢谢,请提出一个解决方案剃刀在更新的OP示例 – Serge

+0

@Serge这是否有帮助? – Iqon

+0

我也有这个想法,最后被遗弃,因为是不可读的...把它放在代码中我只会理解它是什么意思...... @evk示例更具可读性......最后我使用了Integer解决方案.. 。我没有找到一个好的解决方案,我的东西... – Serge