C# 如何控制变量的最大值?

C# 如何控制变量的最大值?,c#,int,global-variables,console-application,C#,Int,Global Variables,Console Application,正如标题所说,我想将技能、stam和luck整数的最大值设置为相关的*Max整数的值。*Max int值在程序启动期间随机设置,常规值在程序运行期间更改。在一些情况下,*最大值在播放过程中可能会增加或减少 public static int skillMax = 0; public static int stamMax = 0; public static int luckMax = 0; public static int skill = skillMax; public static int

正如标题所说,我想将技能、stam和luck整数的最大值设置为相关的*Max整数的值。*Max int值在程序启动期间随机设置,常规值在程序运行期间更改。在一些情况下,*最大值在播放过程中可能会增加或减少

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
赋值。属性也可以只有getter或setter

属性
Cans
将其值存储在所谓的支持字段中。这里
m_cans
。setter通过关键字
value
获取新值

Math.Min(值,10)
返回两个参数中的最小值。例如,如果
为8,则将8分配给
m_罐
。如果
为12,则将10分配给
多个罐

您可以像这样使用此属性

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;
属性有助于实现


您可以轻松地将此示例改编为您的变量。类级变量(字段)通常在前面加上
,以区别于局部变量,即方法中声明的变量。属性是用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;
}

我花了一点时间来理解如何正确地实施它。但一旦我做到了,它就完美地工作了!非常感谢你!