問題描述
將 VBA 選擇案例轉換為 C# (Convert VBA select case to C#)
Select Case True
Case Not A.Name Is Nothing
Set Name = A.Name
Case Not A.Age Is Nothing
Set Age = A.Age
Case Not A.School Is Nothing
Set School = A.School
End Select
在VB中Select Case True
是允許使用的。但對於 C#,它給出了一個錯誤。如何將此 VB 代碼轉換為 C#?
參考解法
方法 1:
There is no direct analog in C# because C# case labels must be constant expressions. Select Case True
is an unusual construct that serves as an alternative to if‑else
constructs.
I suggest replacing it with the far more common pattern:
if (A.Name != null)
Name = A.Name;
if (A.Age != null)
Age = A.Age;
// ... etc
方法 2:
Using switch case in c# is some different. I think this example can be able to useful to you.
using System;
using System.Collections.Generic;
using System.Linq;
public class Example
{
public static void Main()
{
var values = new List<object>();
for (int ctr = 0; ctr <= 7; ctr++) {
if (ctr == 2)
values.Add(DiceLibrary.Roll2());
else if (ctr == 4)
values.Add(DiceLibrary.Pass());
else
values.Add(DiceLibrary.Roll());
}
Console.WriteLine($"The sum of { values.Count } die is { DiceLibrary.DiceSum(values) }");
}
}
public static class DiceLibrary
{
// Random number generator to simulate dice rolls.
static Random rnd = new Random();
// Roll a single die.
public static int Roll()
{
return rnd.Next(1, 7);
}
// Roll two dice.
public static List<object> Roll2()
{
var rolls = new List<object>();
rolls.Add(Roll());
rolls.Add(Roll());
return rolls;
}
// Calculate the sum of n dice rolls.
public static int DiceSum(IEnumerable<object> values)
{
var sum = 0;
foreach (var item in values)
{
switch (item)
{
// A single zero value.
case 0:
break;
// A single value.
case int val:
sum += val;
break;
// A non‑empty collection.
case IEnumerable<object> subList when subList.Any():
sum += DiceSum(subList);
break;
// An empty collection.
case IEnumerable<object> subList:
break;
// A null reference.
case null:
break;
// A value that is neither an integer nor a collection.
default:
throw new InvalidOperationException("unknown item type");
}
}
return sum;
}
public static object Pass()
{
if (rnd.Next(0, 2) == 0)
return null;
else
return new List<object>();
}
}
You can give more information here about switch case
方法 3:
Your VBA code mimics an If‑Then‑ElseIf ...
block, so how about:
if (A.Name != null)
{
Name = A.Name;
}
else if (A.Age != null)
{
Age = A.Age;
}
else if (A.School != null)
{
School = A.School;
}
(by Ramesh Perera、Eric J.、Arash Yazdani、Gustav)