【发布时间】:2025-12-21 21:10:16
【问题描述】:
我正在制作一个 RPG,我有一个怪物遭遇函数,我在其中为敌人的攻击添加权重和模式,并且在调用该函数时我可以对其进行编辑:
数组和变量可以同时作为同一个函数的参数吗?如果没有,是否有其他方法可以实现相同的目标?
static void MonsterEncounter(float hp = 10, float speed = 3, float attack = 2, string monName = "Monster", float exp = 200F, float gold = 30, bool boss = false, bool doubleBattle = false, bool twoEnemy = false, float hpTwo = 10, float speedTwo = 10, float attackTwo = 1, string monNameTwo = "Monster 2", int teamMate = 0, string status = "Fine", string powerAttack = "Super Hit", float powerAttackHit = 10, float powerAttackHeal = 2, bool isHealing = false, bool isDefending = false, int waitTime = 0, string statusAfflict = "null", bool hasWeight = true, bool hasPattern = false, string statusTwo = "Fine",string powerAttackTwo = "Super Hit", float powerAttackHitTwo = 10, float powerAttackHealTwo = 2, bool isHealingTwo = false, bool isDefendingTwo = false, int waitTimeTwo = 0,string statusAfflictTwo = "null", bool hasWeightTwo = true, bool hasPatternTwo = false, int[] patternTwo = {1, 1, 1, 1, 1,1 ,1, 1, 1, 1}, int[] weight = {0, 0, 0, 0}, int[] pattern = {1, 1, 1, 1, 1,1 ,1, 1, 1, 1}, int[] weightTwo = {0, 0, 0, 0})
但这是相关的:
int[] patternTwo = {1, 1, 1, 1, 1,1 ,1, 1, 1, 1}, int[] weight = {0, 0, 0, 0}, int[] pattern = {1, 1, 1, 1, 1,1 ,1, 1, 1, 1}, int[] weightTwo = {0, 0, 0, 0}
但我在这里一直收到同样的错误:
main.cs(4265,254): error CS1525: Unexpected symbol '{'
main.cs(4265,255+): error CS1737: Optional parameter cannot precede required parameters
main.cs(4265,254): error CS1525: Unexpected symbol '1'
我尝试过以不同的方式声明变量:
int[] patternTwo = new int[10] {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, int[] weight = new int[4] {0, 0, 0, 0}, int[] pattern = new int[10] {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, int[] weightTwo = new int[4] {0, 0, 0, 0}
但它仍然产生错误:
main.cs(4265,255+): error CS1736: The expression being assigned to optional parameter 'patternTwo' must be a constant or default value
main.cs(4265,255+): error CS1736: The expression being assigned to optional parameter 'weight' must be a constant or default value
main.cs(4265,255+): error CS1736: The expression being assigned to optional parameter 'pattern' must be a constant or default value
main.cs(4265,255+): error CS1736: The expression being assigned to optional parameter 'weightTwo' must be a constant or default value
我通过谷歌搜索,但我找到的页面要么使用不同的编程语言,要么不涵盖我的要求。
Can I pass an array as arguments to a method with variable arguments in Java?
c# method with unlimited params or method with an array or list?
Passing arrays as arguments (C# Programming Guide)
Passing arrays as arguments in C#
数组和变量可以同时作为同一个函数的参数吗?如果没有,是否有其他方法可以实现相同的目标?
【问题讨论】:
-
为什么不在类或结构中传递它们呢?
-
简短回答。是的。或者,您可以创建一个对象并调用该对象而无需传递参数。您可以拥有任意数量的参数,但是随着程序的增长,这可能会导致问题并成为意大利面条代码。你应该看看面向对象的编程来防止这样的问题。
-
你的方法声明太长了。不要那样做。只需传递一个对象
-
如何创建对象来传递参数?
-
这能回答你的问题吗? Method parameter array default value你实际上遇到了不能给数组一个默认值的问题。拥有数组和非数组参数类型不是问题。