Unity中C#嵌套Switch报错:并非所有代码路径都返回值
问题
需要实现一个方法GStoreDis,传入17/21/25时返回对应商场的3个店铺宽度列表(随机二选一布局),目前仅完成了25单位的逻辑,但Unity控制台持续报错not all code paths return a value。
各宽度对应的店铺布局:
- 17单位商场:
- 布局1:(10,5,2)
- 布局2:(7,5,5)
- 21单位商场:
- 布局1:(10,6,5)
- 布局2:(7,7,7)
- 25单位商场:
- 布局1:(10,10,5)
- 布局2:(9,8,8)
当前实现的代码:
private List<int> GStoreDis(int StoreBlockLength) { switch (StoreBlockLength) { case 25: switch (Random.Range(1,3 )) //Roll out 1 or 2 { case 1: var List2501 = new List<int>() { 10,10,5 }; return List2501; case 2: var List2502 = new List<int>() { 9,8,8 }; return List2502; } default: Debug.Log("Input must be 17 / 21 / 25"); break; } }
报错原因与修复方案
1. 报错核心原因
C#强制要求方法的所有代码路径必须返回对应类型的值,你的代码存在两个不符合要求的地方:
- 外层
switch的case 25分支里,嵌套的switch虽然逻辑上只会返回1或2,但编译器无法识别UnityRandom.Range(1,3)的具体行为,会判定这个分支存在无返回的可能。 default分支只执行了日志输出,没有返回List<int>类型的值。
2. 完整修复代码
先补全17、21单位的逻辑,同时给所有分支加上明确的返回值:
private List<int> GStoreDis(int StoreBlockLength) { switch (StoreBlockLength) { case 17: // 随机选布局1或2 return Random.Range(1, 3) == 1 ? new List<int>() { 10, 5, 2 } : new List<int>() { 7, 5, 5 }; case 21: return Random.Range(1, 3) == 1 ? new List<int>() { 10, 6, 5 } : new List<int>() { 7, 7, 7 }; case 25: return Random.Range(1, 3) == 1 ? new List<int>() { 10, 10, 5 } : new List<int>() { 9, 8, 8 }; default: Debug.Log("Input must be 17 / 21 / 25"); // 返回空列表作为默认值,也可根据需求抛出异常 return new List<int>(); } }
3. 优化建议(可选)
如果后续需要新增更多宽度的布局,可以把数据和逻辑分离,用字典存储布局,代码更易维护:
// 提前定义所有布局数据 private Dictionary<int, List<List<int>>> _storeLayouts = new Dictionary<int, List<List<int>>>() { {17, new List<List<int>>() { new List<int>{10,5,2}, new List<int>{7,5,5} } }, {21, new List<List<int>>() { new List<int>{10,6,5}, new List<int>{7,7,7} } }, {25, new List<List<int>>() { new List<int>{10,10,5}, new List<int>{9,8,8} } } }; private List<int> GStoreDis(int StoreBlockLength) { if (_storeLayouts.TryGetValue(StoreBlockLength, out var layouts)) { // 随机返回一个布局 return layouts[Random.Range(0, layouts.Count)]; } else { Debug.Log("Input must be 17 / 21 / 25"); return new List<int>(); } }
内容的提问来源于stack exchange,提问作者Carta Issue
相关产品推荐
相关产品推荐

