繁体   English   中英

C# - if语句中断

[英]C# - Break out of case if statement

我只是想知道在 C# 中打破 case if 语句的最有效方法是什么?

case UserA:
{
    if (ConfigurationHelper.GetValue("Environment") == "DEV")
    {
        //upload document for Dev env         
    }
    else if (ConfigurationHelper.GetValue("Environment") == "UAT")
    {
        //upload document for UAT env                            
    }

会是以下吗? 还是有更好的方法来做到这一点?

case UserA:
{
    if (ConfigurationHelper.GetValue("Environment") == "DEV")
    {
        //upload document for Dev env 
        break;
    }
    else if (ConfigurationHelper.GetValue("Environment") == "UAT")
    {
        //upload document for UAT env   
        break;                         
    }

你不需要打破 if... else if 语句。 if...else if 块将只执行一个块,而不管使用了多少块。

case UserA:
                        
         if (ConfigurationHelper.GetValue("Environment") == "DEV")
         {
              //upload document for Dev env 
         }                                  
         else if (ConfigurationHelper.GetValue("Environment") == "UAT")
         {
              //upload document for UAT env                         
         }
        break; //you can use break at the end of the if...else if blocks


您可以在循环、case 语句中使用 break。 这是switch case的结构。

switch(expression) 
{
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
    break;
}

不能使用break的地方。 [修改的]

namespace Test
{
    class TestClass{         
        static void Main(string[] args)
        {
            int a=5;
            if(a==1)
            {
               //do something.
               //here break can't be used. actually, there's no need to use break. 
               //as only one block will be executed of the if...else if...else blocks
            }
            else
            {
               //do something
            }
        }
    }
}

什么方法最有效

我不敢相信没有人提出最明显的解决方案。 所以,让我来做吧。 这是在 C# 中使用零代码处理不同环境的方法:

  1. 创建一个名为appsettings.X.json的文件,其中X等于ASPNETCORE_ENVIRONMENT环境变量的值。
  2. 在那里添加特定于环境的配置。
  3. 完毕! 您的ConfigurationHelper将自动从正确的文件中提取值。

当然,这种方法有一些限制(例如,您不能同时使用两种配置)。 希望对你有效。

case UserA:
{
   switch(ConfigurationHelper.GetValue("Environment"))
   {
        case "DEV":
             //upload document for Dev env 
             break;
        case "UAT":
             //upload document for UAT env   
             break;
        default:
             break;
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM