【问题标题】:Writing an "if" condition in C# but there will not be any code written inside it在 C# 中编写“if”条件,但其中不会编写任何代码
【发布时间】:2023-04-08 14:11:01
【问题描述】:

我有一个 DataTable pgRestrictionTbl :

pgRestrictionTbl = GetDataTable(ProjectID, sgID)

我写了一个“if”条件,其中我又写了“if and else”条件。

if()
{
    if()
    {
         KnownErrorException.Throw("eSGNTRSTRCTD");
    }
    else
    {
          KnownErrorException.Throw("eSGNKKTURSTRCTD");
    }
}
else
{
    if()
    {
       // I dont need any code to be execute in this block
    }
    else
    {
        KnownErrorException.Throw("eSGNTRHJISTRCTD");
    }
}

method call();

在所有这些条件之后有一些代码。 现在如果我的条件在 elseif 条件下为真,我需要执行所有这些条件之外的代码方法调用。 我不想写任何 goto 标签。还有其他方法吗?有人可以帮忙吗?

我在没有在 if 条件下编写任何代码的情况下进行了尝试,但我认为这不是一种有效的方法。

【问题讨论】:

  • -1 没有缩进,无效代码,一些关于未出现在代码中的数据表的注释..
  • if 子句为空不存在效率问题。首先对其进行编码以确保正确性,然后是可读性(这可能是也可能不是您所拥有的;鉴于您的伪代码,这很难说)。

标签: c# if-statement conditional-statements


【解决方案1】:

只是反转 if?

if()
{
if()
{
 KnownErrorException.Throw("eSGNTRSTRCTD");
}
else
{
  KnownErrorException.Throw("eSGNKKTURSTRCTD");
}
}
else
{
if(!expr)
{
KnownErrorException.Throw("eSGNTRHJISTRCTD");
}
}

【讨论】:

    【解决方案2】:

    你可以试试:

    if(cond1)
    {
      if(cond2)
      {
       KnownErrorException.Throw("eSGNTRSTRCTD");
      }
      else
      {
        KnownErrorException.Throw("eSGNKKTURSTRCTD");
      }
    }
    else if(!cond3)
    {
      KnownErrorException.Throw("eSGNTRHJISTRCTD");
    }
    

    【讨论】:

      【解决方案3】:

      这只是风格和惯例的问题。没有一个正确的答案。

      有些人会争辩说要颠倒逻辑,所以不需要有问题的分支。

      其他人会争辩要包含分支并在其中添加评论说不需要做任何事情,只是为了表明该分支已被考虑并且没有被错误地遗漏。

      总结:做对你或你目前工作/学习地点的人最有意义的事情

      【讨论】:

        【解决方案4】:

        我认为如果您结合以下条件,您的生活会更轻松:

        if(condition1 && condition2) // Combine conditions
        {
           KnownErrorException.Throw("eSGNTRSTRCTD");
        }
        else if(condition1Only)
        {
           KnownErrorException.Throw("eSGNKKTURSTRCTD");
        }
        else
        {
           // Since there in no sense to have an IF statement with no statements then no need to define it.
           KnownErrorException.Throw("eSGNTRHJISTRCTD");
        }
        
        // Congratulation, you have all valid inputs, it is safe to call a method.
        methodCall();
        

        【讨论】:

          猜你喜欢
          • 2021-10-16
          • 2011-12-23
          • 2016-10-25
          • 1970-01-01
          • 2016-12-06
          • 1970-01-01
          • 1970-01-01
          • 2013-08-17
          • 1970-01-01
          相关资源
          最近更新 更多