【发布时间】:2018-09-28 04:15:46
【问题描述】:
所以让我先说我是 C# 新手。我有一个 switch 语句,目前有 10 种不同的情况,但是,我需要使用它 3 次不同的时间(相同的 10 种情况,每种情况的结果不同),每种情况只有轻微的变化。
我觉得我只是在重复代码,有没有办法缩短它?
//Set the growth time of the crop based on what cropType.
switch (cropType) {
case 1:
//Potatoes
growth = 60;
break;
case 2:
//Strawberries
growth = 80;
break;
case 3:
//Cabbages
growth = 90;
break;
case 4:
//Carrots
growth = 40;
break;
case 5:
//Melon
growth = 120;
break;
case 6:
//Pumpkin
growth = 130;
break;
case 7:
//Eggplant
growth = 50;
break;
case 8:
//Mushroom
growth = 70;
break;
case 9:
//Wheat
growth = 40;
break;
case 10:
//Truffle
growth = 150;
break;
}
这是我的 1 部分代码。在第二部分中,我根据情况分配了一个图像,这必须单独完成,因为它依赖于增长和变化,而增长则不。我实际上并没有在其他开关上使用它。这是我在下面的另一个:
switch (cropType) {
case 1:
//Potatoes
Debug.Log("Potatoes Harvested!");
Global.potato += 2;
break;
case 2:
//Strawberries
Debug.Log("Strawberries Harvested!");
Global.strawberry += 4;
break;
case 3:
//Cabbages
Debug.Log("Cabbages Harvested!");
Global.cabbage += 1;
break;
case 4:
//Carrots
Debug.Log("Carrots Harvested!");
Global.carrot += 3;
break;
case 5:
//Melon
Debug.Log("Melons Harvested!");
Global.melon += 1;
break;
case 6:
//Pumpkin
Debug.Log("Pumpkins Harvested!");
Global.pumpkin += 1;
break;
case 7:
//Eggplant
Debug.Log("Eggplant Harvested!");
Global.eggplant += 2;
break;
case 8:
//Mushroom
Debug.Log("Mushrooms Harvested!");
Global.mushroom += 4;
break;
case 9:
//Wheat
Debug.Log("Wheat Harvested!");
Global.wheat += 6;
break;
case 10:
//Truffle
Debug.Log("Truffles Harvested!");
Global.truffle += 1;
break;
}
基本上,它是一个脚本,需要根据其中的cropType 做不同的事情。
【问题讨论】:
-
首先使用有意义的
enum CropType { Potatoes = 1, Strawberries = 2, Cabbages = 3, ... }而不是数字如何?然后将成长信息放入Dictionary<CropType, int> { { CropType.Potatoes, 60 }, { CropType.Strawberries, 80 }, ... },然后像var growth = growthDictionary[cropType];一样使用。 -
如果你有一个多态的
Crop类型,你就不需要这样做了。您可以使用Growth属性定义基本Crop类,然后从中派生Mushroom和Eggplant之类的类型,并使用提供适当值的Growth的重写实现。这意味着您还可以不必将数字映射到作物。 -
@spender - 是的,现在有了第二个例子,看起来 OP 可能想要一个
class Crop { public CropType Type { get; set; } public string Name { get; set; }, public int Growth { get; set; } public int ItemsPerHarvest { get; set; } [...] } -
这听起来像是您第二次更新后的xy problem。我认为您应该在此处发布有关您真正想要实现的目标的更多详细信息。最初听起来您想简化
switch,但现在听起来您遇到了类设计问题。 -
@spender 是的,我认为一个类肯定会在这里工作,因为我从其他类中获取了很多作物,而不仅仅是这个类。我可能不会仅仅因为我的时间有限,因为这是一项任务(我们的任务是“做点什么”),但如果我有时间,它会在我的名单上排名第一:)
标签: c# unity3d switch-statement