如何访问和创建if语句变量C# [英] How to access and create if statement variables C#

查看:181
本文介绍了如何访问和创建if语句变量C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图保持DRY原则在C#中,我在想,如果有可能,如果块访问的参数检查。例如,将下面的可能呢?



 如果(foo的== ||真吧==假)
{
如果(check0)
{
// foo的是真实的
}
如果(!CHECK1)
{
//酒吧假
}
}

我也想知道如果有可能做到这一点,保持清洁范围:

 如果(VAR富= runTimeAccessedVariable ==栏)
$ { b $ b //我们现在有运行时生成的变量。
}
//但这里不存在


解决方案

不,这是不可能的。实际上,由于您使用短路 || 运营商,第二次检查甚至可能不会进行评估。



显然,你可以解决它,如下所示:

  VAR fooIsTrue =(富== TRUE); 
VAR barIsFalse =(巴==假);

如果(fooIsTrue || barIsFalse)
{

}

请注意,这会更改你的代码的行为,因为 barIsFalse 总是被判断。


I'm trying to keep to the DRY principle in C#, and I was wondering if it's possible to access the argument checks in an if block. For example, would the below be possible?

if (foo == true || bar == false)
{
  if (check0)
  {
    //foo is true
  }
  if (!check1)
  {
    //bar is false
  }
}

I was also wondering if it's possible to do this, to keep the scope clean?:

if (var foo = runTimeAccessedVariable == "bar")
{
  //we now have the runtime generated variable.
}
//but it doesn't exist here

解决方案

Nope, it's not possible. In fact, since you use the short-circuiting || operator, the second check might not even be evaluated.

Obviously, you can work around it as follows:

var fooIsTrue = (foo == true);
var barIsFalse = (bar == false);

if (fooIsTrue || barIsFalse)
{
    ...
}

Note that this changes the behaviour of your code, since barIsFalse is always evaluated.

这篇关于如何访问和创建if语句变量C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆