我在AS3中编写了一个代码,它允许我检查特定数量的事情是否真实......
If (true + false + true + true + false + true + true < 4)
{
}
Run Code Online (Sandbox Code Playgroud)
当我尝试用C#重写时,它告诉我我不能添加bool和bool类型.最好的方法是这样重写它吗?或者是否有一些更简单的工作?
If ((true?1:0) + (false?1:0) + (true?1:0) + (true?1:0) + (false?1:0) + (true?1:0) + (true?1:0) < 4)
{
}
Run Code Online (Sandbox Code Playgroud)
Joe*_*rra 60
尝试在方法参数上使用IEnumerable<T>.Count(Func<T,bool>)from System.Linq,with Tas .boolparams
public static int CountTrue(params bool[] args)
{
return args.Count(t => t);
}
Run Code Online (Sandbox Code Playgroud)
用法
// The count will be 3
int count = CountTrue(false, true, false, true, true);
Run Code Online (Sandbox Code Playgroud)
您还可以介绍一种this扩展方法:
public static int TrueCount(this bool[] array)
{
return array.Count(t => t);
}
Run Code Online (Sandbox Code Playgroud)
用法
// The count will be 3
int count = new bool[] { false, true, false, true, true }.TrueCount();
Run Code Online (Sandbox Code Playgroud)
slo*_*oth 16
您可以创建一个数组并使用Count:
if ((new []{true, false, true, true, false, true, true}).Count(x=>x) < 4)
{
}
Run Code Online (Sandbox Code Playgroud)
或Sum方法:
if ((new []{true, false, true, true, false, true, true}).Sum(x=>x?1:0) < 4)
{
}
Run Code Online (Sandbox Code Playgroud)
por*_*ges 13
这是一个更有趣的例子:
if ((BoolCount)true + false + true + true + false + true + true <= 5)
{
Console.WriteLine("yay");
}
Run Code Online (Sandbox Code Playgroud)
使用这个类:
struct BoolCount
{
private readonly int c;
private BoolCount(int c) { this.c = c; }
public static implicit operator BoolCount(bool b)
{ return new BoolCount(Convert.ToInt32(b)); }
public static implicit operator int(BoolCount me)
{ return me.c; }
public static BoolCount operator +(BoolCount me, BoolCount other)
{ return new BoolCount(me.c + other.c); }
}
Run Code Online (Sandbox Code Playgroud)
Convert.ToInt32(true) + Convert.ToInt32(false) + Convert.ToInt32(true) 在这种情况下也有效,我认为这是我们最简单的方法
| 归档时间: |
|
| 查看次数: |
8500 次 |
| 最近记录: |