[英]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# 中使用零代碼處理不同環境的方法:
appsettings.X.json
的文件,其中X
等於ASPNETCORE_ENVIRONMENT
環境變量的值。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.