如何将字典中的所有负值设置为零?

Zaf*_*aro 2 c# dictionary

在lil'c#浏览器游戏中工作,我使用这个字典来跟踪游戏中的几个资源:

public Dictionary <String, int> resource = new Dictionary<string,int>();
Run Code Online (Sandbox Code Playgroud)

Amoungst那些"金",每个滴答都会改变.

protected void timerMinute_Tick(object sender, EventArgs e)
{
resource["gold"] += (resProduction["gold"] - resConsumption["gold"])
}
Run Code Online (Sandbox Code Playgroud)

现在,如果消费量大于产量,则数量会减少.我想否认资源变得消极.我知道我可以为每个刻度执行此操作:

if (resource["gold"] < 0)
{
resource["gold"] = 0;
}
Run Code Online (Sandbox Code Playgroud)

不过,我有很多很多的资源,以保持轨道上,所以当我可以写上述各代码,我只是想知道,如果有人有一个聪明的方法来检查字典中的所有值的资源,并把任何消极转化为零.

编辑:感谢您对此问题的所有好建议!作为c#的新手,我对它并不是很熟悉^^

Tim*_* S. 8

您可以创建自己的字典类,以确保值为非负值.这是一个简单的例子,但你可以很容易地使它具有通用性和可扩展性.

public class ValidatedDictionary : IDictionary<string, int>
{
    private Dictionary<string, int> _dict = new Dictionary<string, int>();
    protected virtual int Validate(int value)
    {
        return Math.Max(0, value);
    }
    public void Add(string key, int value)
    {
        _dict.Add(key, Validate(value));
    }

    public bool ContainsKey(string key)
    {
        return _dict.ContainsKey(key);
    }
    // and so on: anywhere that you take in a value, pass it through Validate
Run Code Online (Sandbox Code Playgroud)