如何编写一个开关表达式来支持多个返回相同结果的情况?
对于版本8之前的c#,可能会这样编写一个开关:
var switchValue = 3;
var resultText = string.Empty;
switch (switchValue)
{
case 1:
case 2:
case 3:
resultText = "one to three";
break;
case 4:
resultText = "four";
break;
case 5:
resultText = "five";
break;
default:
resultText = "unkown";
break;
}
Run Code Online (Sandbox Code Playgroud)
当我使用C#版本8表达式语法时,如下所示:
var switchValue = 3;
var resultText = switchValue switch
{
1 => "one to three",
2 => "one to three",
3 => "one to three",
4 => "four",
5 => "five",
_ => "unknown",
};
Run Code Online (Sandbox Code Playgroud)
所以我的问题是:如何将案例1,2和3变成一个开关案例臂,从而不需要重复该值? …
我有一个简单的方法,它接受一个枚举并返回一个字符串:
public static String enumToString(MyEnum type) {
return switch (type) {
case Enum1 -> "String_1";
case Enum2 -> "String_2";
case Enum3 -> "String_3";
case Enum4 -> "String_4";
case Enum5 -> "String_5";
case Enum6 -> "String_6";
default -> null;
};
}
Run Code Online (Sandbox Code Playgroud)
但是声纳给了我这个 Major error: Unused method参量应该被删除。
正如您所看到的,参数类型用于开关中。有关更多详细信息,当我使用旧开关盒时,一切正常。
关于这个问题有什么想法吗,sonar 是否涵盖了新的 Java 语法?
嗯,我注意到当我移除default -> null;声纳时正确通过!这很奇怪。
public static String enumToString(MyEnum type) {
return switch (type) {
case Enum1 -> "String_1";
case Enum2 -> "String_2";
case Enum3 -> "String_3";
case Enum4 …Run Code Online (Sandbox Code Playgroud) 我不知道如何使switch表达式产生一个ref值。
bool cond = true;
int a = 1, b = 2;
// This works
ref int c = ref cond ? ref a : ref b;
// But using a switch expression fails to compile.
// Error CS1525 Invalid expression term 'ref'
c = ref (cond switch { true => ref a, false => ref b });
Run Code Online (Sandbox Code Playgroud)
我的语法有误吗?这有可能吗?
无论是否包含外部,它都不会编译ref ( )。我bool只是为了快速说明问题而使用,但是我的实际用例并不是那么简单。
我找不到解决此问题的文档。(也许我只是不擅长使用谷歌......)我的猜测是答案是否定的,但是我不明白文档中在哪里解决了这个问题。准确地说,我的问题如下。
假设,我想执行这样的事情:
DirectoryInfo someDir = new DirectoryInfo(@".\someDir");
Console.WriteLine($"Would you like to delete the directory {someDir.FullName}?");
string response = Console.ReadLine().ToLower();
response switch
{
"yes" => { someDir.Delete(); ... MoreActions},
_ => DoNothing()
};
Run Code Online (Sandbox Code Playgroud)
我知道我可以通过使用常规 switch 或 if/else 来实现所需的行为,但是我很好奇在这种情况下是否可以使用 switch 表达式。
希望通过这个标题,我显然不是在问 Swift 是否支持 Switch 语句。我特别询问 Swift 是否支持 Switch表达式,类似于 C# 所支持的。
差异很微妙,但很重要。Switch 语句是一种根据特定情况对代码行进行分组的方法。然而,Switch 表达式会根据特定情况返回一个值。
假设您有以下枚举...
enum SomeEnum {
case a
case b
case c
}
Run Code Online (Sandbox Code Playgroud)
现在假设您需要根据特定的 switch 语句计算/返回一些值。目前,在 Swift 中,您必须使用 Switch语句来执行此操作......
let someEnumValue: SomeEnum = .a
let result: String
switch someEnumValue {
case .binary: result = "This is the 'A' type"
case .octal: result = "This is the 'B' type"
case .hexadecimal: result = "This is the 'C' type"
}
print(result)
//prints 'This is the 'A' …Run Code Online (Sandbox Code Playgroud) 在 C# 8 中,引入了 switch 表达式。如果 switch 表达式不是详尽的,会发生什么?换句话说,如果我不测试每个可能的值会发生什么?
static void Main(string[] args)
{
int x = 1;
int imExhaustive = x switch
{
3 => 4,
_ => 0 // x = 1 matches this
};
int okFine = x switch
{
1 => 4 // x = 1 matches this
};
int noMatch = x switch
{
3 => 4 // No match
};
}
Run Code Online (Sandbox Code Playgroud) 我正在 IntelliJ 2022.2 中使用 java 17 进行开发。
在某些情况下'switch' expression does not cover all possible input values会显示,但在某些情况下不会显示。我想弄清楚为什么。
假设这entityType是一个包含 3 个值的枚举,我添加了第四个值TYPE_D。所以我希望'switch' expression does not cover all possible input values在switch.
当显示时:
public Map<String, String> getRecordDetails() {
return switch (entityType) {
case TYPE_A -> Map.of("A","A");
case TYPE_B -> Map.of("B","B");
case TYPE_C -> Map.of("C","C");
};
}
Run Code Online (Sandbox Code Playgroud)
未显示:
public String getRecordDetails() {
StringBuilder stringBuilder = new StringBuilder();
switch (entityType) {
case TYPE_A -> stringBuilder.append("A");
case TYPE_B …Run Code Online (Sandbox Code Playgroud) 我尝试在 IntelliJ 中使用 Java 12,但是当我尝试运行我的应用程序时出现错误
Error:(57, 32) java: switch expressions are a preview feature and are disabled by default.
(use --enable-preview to enable switch expressions)
Run Code Online (Sandbox Code Playgroud)
我在应用程序配置 VM 选项中添加了 --enable-preview 但仍然出现此错误。我添加了 SDK 路径。任何人都知道我做错了什么?
List<Car> sortedCars = switch (sortType) {
case COLOR -> cars.stream().sorted(Comparator.comparing(Car::getColor)).collect(Collectors.toList());
case MILEAGE -> cars.stream().sorted(Comparator.comparing(Car::getMileage)).collect(Collectors.toList());
case MODEL -> cars.stream().sorted(Comparator.comparing(Car::getModel)).collect(Collectors.toList());
case PRICE -> cars.stream().sorted(Comparator.comparing(Car::getPrice)).collect(Collectors.toList());
};
Run Code Online (Sandbox Code Playgroud) java intellij-idea switch-statement java-12 switch-expression
我想在我的代码中使用新的开关,对于方法结果 make log 并 return IActionResult。
我尝试做这样的事情:
var response = (this._coreRepository.Write(value.Content, data.Id.ToString())); \\return bool
return response switch
{
true => () =>
{
this._log.LogInformation("Write is complited");
return Ok();
},
false => () =>
{
this._log.LogInformation("Error in writing");
return BadRequest();
},
_ => () =>
{
throw new Exception("Unexpected error");
}
};
Run Code Online (Sandbox Code Playgroud)
但编译器对我说cannot convert lambda expression to type 'IActionResult' because it is not a delegate type。
我该如何修复它?
我不明白为什么第一个片段编译得很好:
var res = getResult(s);
public static double getResult(Shape s) {
switch(s) {
case Rectangle r : return 2* r.largeur() + 2* r.longueur();
case Circle c : return 2*c.radius();
default : throw new RuntimeException("not a shape");
}
}
Run Code Online (Sandbox Code Playgroud)
但不是这个:
var res = switch(s) {
case Rectangle r : return 2* r.largeur() + 2* r.longueur();
case Circle c : return 2*c.radius();
default : throw new RuntimeException("not a shape");
};
Run Code Online (Sandbox Code Playgroud)
对我来说看起来是一样的。