正如标题所说,我想将技能,stam和运气整数的最大值设置为相关* Max整数的值。 * Max int值在程序启动期间随机设置,并且在整个程序运行期间更改常规值。在游戏过程中可能会出现一些* Max值增加或减少的情况。
public static int skillMax = 0;
public static int stamMax = 0;
public static int luckMax = 0;
public static int skill = skillMax;
public static int stam = stamMax;
public static int luck = luckMax;
由于我对C#的了解还处于起步阶段,我还没有尝试过多少。但是我在互联网上进行了广泛的搜索,但是除了MinValue和MaxValue字段以及没有任何解释的这段代码之外,我找不到任何东西:
protected int m_cans;
public int Cans
{
get { return m_cans; }
set {
m_cans = Math.Min(value, 10);
}
}
提前感谢您提出的任何建议!
代码说明:Cans
是一个属性。属性提供对类或结构字段(变量)的受控访问。它们由两个名为get
的方法组成,用于返回值,set
用于赋值。物业也可以只有一个吸气剂或只有一个二传手。
Cans
属性将其值存储在所谓的支持字段中。在这里m_cans
。 setter通过关键字value
获取新值。
Math.Min(value, 10)
返回两个参数中的最小值。即,例如,如果value
是8,则将8分配给m_cans
。如果value
是12,则将10分配给m_cans
。
您可以像这样使用此属性
var obj = new MyCalss(); // Replace by your real class or struct name.
obj.Cans = 20; // Calls the setter with `value` = 20.
int x = obj.Cans; // Calls the getter and returns 10;
属性有助于实现Information hiding的原则。
您可以轻松地将此示例应用于您的变量。通常使用_
对类级别变量(字段)进行前缀,以将它们与局部变量(即方法中声明的变量)区分开来。属性是用PascalCase编写的。
private static int _skillMax; // Fields are automatically initialized to the default
// value of their type. For `int` this is `0`.
public static int SkillMax
{
get { return _skillMax; }
set {
_skillMax = value;
_skill = _skillMax; // Automatically initializes the initial value of Skill.
// At program start up you only need to set `SkillMax`.
}
}
private static int _skill;
public static int Skill
{
get { return _skill; }
set { _skill = Math.Min(value, _skillMax); }
}
创建更新值的方法
private static void UpdateSkill(int newValue)
{
skill = newValue;
skillMax = newValue > skillMax ? newValue : skillMax;
}