使用Boolean切换大小写
本文关键字:大小写 Boolean 使用 | 更新日期: 2023-09-27 18:14:38
我试图为一个项目创建一个前缀文本值。我用的是switch case。当用户选择相关的单选按钮时,我们应该给出前缀值。
"switch()"之后应该给出什么?
来自用户选择的值是布尔值。输出为string
.
的任何帮助 public string officePostfix()
{
string postfix = null;
switch (...)
{
case SheetMgrForm.Goldcoast = true:
postfix = "QLD";
break;
case SheetMgrForm.Melbourne = true:
postfix = "MEL";
break;
case SheetMgrForm.Sydney = true:
postfix = "SYD";
break;
case SheetMgrForm.Brisbane = true:
postfix = "BIS";
break;
}
return postfix;
}
这不是switch
的工作方式。您不能在每个case
中放入任意布尔表达式(假设您指的是==
而不是=
,顺便说一句)。
您需要使用一组if-else
块,如:
if (SheetMgrForm.Goldcoast) {
postfix = "QLD";
} else if (SheetMgrForm.Melbourne) {
postfix = "MEL";
} else if ......
然而,看起来你的设计需要一些返工。拥有所有这些单独的布尔值是笨拙的。
另一种方法是使用枚举来定义您的区域,然后将这些区域映射到资源文件。这使得它更易于维护,例如本地化或将来进一步扩展,如果列表很长,则可能很有用,即通过T4自动创建enum和资源,或者您必须查询web服务,或其他…
例如,您有一个AreaPostfixes
资源文件和一个Area
枚举。
public enum Area
{
Goldcoast,
Melbourne,
// ...
}
public static class AreaExtensions
{
public static string Postfix(this Area area)
{
return AreaPostfixes.ResourceManager.GetString(area.ToString());
}
}
// AreaPostfixes.resx
Name Value
Goldcoast QLD
Melbourne MEL
// Usage
public string GetPostfix(Area area)
{
return area.Postfix();
}
消除了对开关等的任何需要,您唯一需要确保的是每个枚举和资源都有1:1的映射。我通过单元测试做到这一点,但如果GetString在Postfix扩展方法中返回null,则放置Assert或抛出异常很容易。
你可以在c# 8的属性模式中做到这一点:
string officePostfix(SheetMgrForm test) =>
test switch
{
{ GoldCoast: true } => "QLD",
{ Melbourne: true } => "VIC",
{ Sydney: true } => "NSW",
{ Brisbane: true } => "BIS",
_ => string.Empty
};
https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8特性模式
switch
不支持此操作。情况必须是恒定的。案例也必须是唯一的。
你需要把你的布尔属性变成一个enum
并关闭它,或者把你的开关变成一个标准的if
语句
http://msdn.microsoft.com/en-us/library/06tc147t (v = vs.110) . aspx
这可能会返回您想要的结果,但这是一种丑陋的暴力方法。情况部分是期望某种常数。在这种情况下,您将得到"case true:"或"case false:"(尽管我不确定在这种情况下您将如何处理它)。
public string officePostfix()
{
string postfix = null;
switch (SheetMgrForm.Goldcoast == true)
{
case true:
postfix = "QLD";
break;
}
switch(SheetMgrForm.Melbourne == true)
{
case true:
postfix = "MEL";
break;
}
switch (SheetMgrForm.Sydney == true)
{
case true:
postfix = "SYD";
break;
}
switch(SheetMgrForm.Brisbane == true)
{
case true:
postfix = "BIS";
break;
}
return postfix;
}