You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中动态验证数据类型的取值范围?

数据类型范围验证的简化实现方案

问题背景

需要完成课程项目:允许用户选择byte、int、short、long等数据类型,验证数学题输入的数值是否在所选类型的取值范围内。当前通过大量if语句逐个判断类型并检查范围,希望优化实现方式。

现有实现代码

if(numType == BYTE){
  if(leftNum > byte.MaxValue){
    errorsEncountered = true;
    returnString = returnString + "Left number must not be more than " + 
      byte.MaxValue.ToString() + " for a byte.\n";
  }
  if(leftNum < byte.MinValue){
    errorsEncountered = true;
    returnString = returnString + "Left number must not be less than " + 
      byte.MinValue.ToString() + " for a byte.\n";
  }
  // 其他类型的判断逻辑以此类推
}

尝试的优化思路

尝试通过数组记录数据类型,但字符串数组无法直接获取类型的MaxValue和MinValue,因此该思路无法直接运行:

byte numType = 8; // 该值会直接触发错误提示
const byte BYTE = 0;
const byte SHORT = 1;
const byte INT = 2;
const byte LONG = 3;
const byte FLOAT = 4;
const byte DOUBLE = 5;
const byte DECIMAL = 6;
string[] dataTypes = {"byte", "short", "int", "long", "float", "double", "decimal"};
if(leftNum > dataTypes[numType].MaxValue) {
  errorsEncountered = true;
  returnString = "Left number must not be more than " + 
    dataTypes[numType].MaxValue.ToString() + " for a " + dataTypes[numType] + ".";
}
if(leftNum < dataTypes[numType].MinValue) {
  errorsEncountered = true;
  returnString = "Left number must not be more than " + 
    dataTypes[numType].MinValue.ToString() + " for a " + dataTypes[numType] + ".";
}

可行的简化方案

方案1:预存类型范围信息(入门友好)

将每种数据类型的最小值、最大值和名称预存在集合中,通过索引直接获取对应信息,避免重复的if判断:

// 定义整数类型的范围信息集合
var integerTypeInfos = new List<(long Min, long Max, string Name)>
{
    (byte.MinValue, byte.MaxValue, "byte"),
    (short.MinValue, short.MaxValue, "short"),
    (int.MinValue, int.MaxValue, "int"),
    (long.MinValue, long.MaxValue, "long")
};

// 定义浮点类型的范围信息集合
var floatTypeInfos = new List<(double Min, double Max, string Name)>
{
    (float.MinValue, float.MaxValue, "float"),
    (double.MinValue, double.MaxValue, "double"),
    ((double)decimal.MinValue, (double)decimal.MaxValue, "decimal")
};

// 根据numType匹配对应类型信息并检查范围
if (numType <= 3)
{
    var info = integerTypeInfos[numType];
    if (leftNum > info.Max)
    {
        errorsEncountered = true;
        returnString += $"Left number must not be more than {info.Max} for a {info.Name}.\n";
    }
    if (leftNum < info.Min)
    {
        errorsEncountered = true;
        returnString += $"Left number must not be less than {info.Min} for a {info.Name}.\n";
    }
}
else
{
    var info = floatTypeInfos[numType - 4];
    if (leftNum > info.Max)
    {
        errorsEncountered = true;
        returnString += $"Left number must not be more than {info.Max} for a {info.Name}.\n";
    }
    if (leftNum < info.Min)
    {
        errorsEncountered = true;
        returnString += $"Left number must not be less than {info.Min} for a {info.Name}.\n";
    }
}

方案2:利用反射动态获取类型信息(进阶)

通过反射API动态获取每种数据类型的MinValue和MaxValue,代码更简洁,但需要理解反射的基本原理:

// 定义类型数组和对应名称数组
Type[] numericTypes = { typeof(byte), typeof(short), typeof(int), typeof(long), typeof(float), typeof(double), typeof(decimal) };
string[] typeNames = { "byte", "short", "int", "long", "float", "double", "decimal" };

// 获取选中的类型和名称
Type selectedType = numericTypes[numType];
string typeName = typeNames[numType];

// 动态获取MinValue和MaxValue
dynamic minValue = selectedType.GetField("MinValue").GetValue(null);
dynamic maxValue = selectedType.GetField("MaxValue").GetValue(null);

// 执行范围检查
if (leftNum > maxValue)
{
    errorsEncountered = true;
    returnString += $"Left number must not be more than {maxValue} for a {typeName}.\n";
}
if (leftNum < minValue)
{
    errorsEncountered = true;
    returnString += $"Left number must not be less than {minValue} for a {typeName}.\n";
}

补充建议

如果觉得上述方案的原理难以理解,建议先系统学习C#基础内容,比如数据类型、集合操作、反射(进阶)等核心知识点,打好基础后再理解这些优化逻辑会更顺畅。

内容的提问来源于stack exchange,提问作者Silky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 02:15:35