Joe*_*Joe 26 c# idiomatic operators
假设我正在使用类的对象thing.我得到这个对象的方式有点罗嗦:
BigObjectThing.Uncle.PreferredInputStream.NthRelative(5)
Run Code Online (Sandbox Code Playgroud)
我想看看这thing是否等于x或y或z.写这个的天真方式可能是:
BigObjectThing.Uncle.PreferredInputStream.NthRelative(5) == x ||
BigObjectThing.Uncle.PreferredInputStream.NthRelative(5) == y ||
BigObjectThing.Uncle.PreferredInputStream.NthRelative(5) == z
Run Code Online (Sandbox Code Playgroud)
在某些语言中,我可以这样写:
BigObjectThing.Uncle.PreferredInputStream.NthRelative(5) == x |= y |= z
Run Code Online (Sandbox Code Playgroud)
但C#不允许这样做.
是否有一种C#-idiomatic方法将此测试编写为单个表达式?
Jac*_*cob 46
只需使用变量:
var relative = BigObjectThing.Uncle.PreferredInputStream.NthRelative(5);
return relative == x || relative == y || relative == z;
Run Code Online (Sandbox Code Playgroud)
或者如果你想得到更多的东西:
var relatives = new HashSet<thing>(new[] { x, y, z });
return relatives.Contains(BigObjectThing.Uncle.PreferredInputStream.NthRelative(5));
Run Code Online (Sandbox Code Playgroud)
C.E*_*uis 24
扩展方法会模拟这个:
public static bool EqualsAny(this Thing thing, params object[] compare)
{
return compare.Contains(thing);
}
bool result = BigObjectThing.Uncle.PreferredInputStream.NthRelative(5).EqualsAny(x, y, z);
Run Code Online (Sandbox Code Playgroud)
C#没有这种类似OR的比较afaik的默认语法.
mcl*_*129 14
正如其他人指出的那样,集合是你可以做到这一点的一种方式.如果你想有比使用多一点的灵活性Contains(这只有真正让你测试x.Equals(y)),甚至支持链接通过&=在additon来|=,我会建议Any或All内置到.NET扩展方法.
var compares = new[] { x, y, z };
var relative = BigObjectThing.Uncle.PreferredInputStream.NthRelative(5);
// Simulate |= behavior
return compares.Any(x => relative == x);
// Simulate &= behavior
return compares.All(x => relative == x);
// A more complex test chained by OR
return compares.Any(x => relative.SomeProperty == x.SomeProperty);
// A less readable but one-line approach
return (new [] {x, y, x}).Any(x => BigObjectThing.Uncle.PreferredInputStream.NthRelative(5) == x);
Run Code Online (Sandbox Code Playgroud)
Set*_*eth 10
您可以将对象放在Collection第一个然后使用Contains().
var relatives = new Collection<Thing> { x, y, z };
if (relatives.Contains(BigObjectThing.Uncle.PreferredInputStream.NthRelative(5)))
{
...
}
Run Code Online (Sandbox Code Playgroud)
这可以进一步缩短(为了便于阅读):
if (new Collection<Thing> { x, y, z }.Contains(BigObjectThing.Uncle.PreferredInputStream.NthRelative(5)))
{
...
}
Run Code Online (Sandbox Code Playgroud)