繁体   English   中英

如何使用 C# 将变量设置为至少最小值

[英]How can I set a variable to be at least a minimum value with C#

我有这个代码:

Current.Resources["CardSetIconWidth"]   = (width-30)/260 * 160;

我想确保Current.Resources["CardSetIconWidth"]始终至少至少为 160。

有没有一种简单的方法可以做到这一点?

尝试这个:

Current.Resources["CardSetIconWidth"] = Math.Max((width - 30) / 260 * 160, 160);

分配后,你可以做

if (Current.Resources["CardSetIconWidth"]<160) Current.Resources["CardSetIconWidth"]=160;

此致

另一种选择是在 class 的索引器中使用@rfmodulator 答案:

public class SafeValues
{
    private readonly IDictionary<string, int> _dict = new Dictionary<string, int>();

    public int this[string key]
    {
        get { return _dict[key]; } // you can also choose to use Math.Min 
                                   // in the getter to keep the original values in the underlying dictionary
                                   // for debug purposes

        set { _dict[key] = Math.Max(value, 160); }
    }
}

所以你可以像这样使用它

var Resources = new SafeValues(); // you can easily set a parameter for the min value in the constructor if you want
Resources["CardSetIconWidth"] = (width-30)/260 * 160;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM