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

如何区分null值是System.String或System.Nullable<int>?泛型转换报错求助

Fixing the Invalid Cast Exception in Your Generic Conversion Method

Let's break down why you're hitting those exceptions and fix the method properly:

What's Causing the Issues?

  1. Wrong Type Handling for Null arg: When arg is null (either string or Nullable<int>), your first branch unconditionally converts the string to int and tries to cast it to T. For string type, this fails because you can't cast an int object directly to string—that's the "invalid cast" error you're seeing.
  2. GetType() Risks for Nullable Types: If arg is a Nullable<int> with no value (HasValue = false), calling arg.GetType() will throw a NullReferenceException. That's because nullable value types get boxed to null when they have no value, so you're trying to call a method on a null object.
  3. Overreliance on Convert: Using Convert.ToInt32 or Convert.ToDecimal will throw exceptions if the string can't be parsed, which makes your method less robust.

Fixed Implementation

Here's a revised version of your method that addresses all these issues:

protected T GetValue<T>(T arg, List<string> item, int index)
{
    // Get the target type, handling nullable types (e.g., int? becomes int)
    var targetType = typeof(T);
    var underlyingType = Nullable.GetUnderlyingType(targetType);
    var effectiveType = underlyingType ?? targetType;

    // Guard clause: avoid out-of-bounds index access
    if (index < 0 || index >= item.Count)
        return default(T);

    string valueStr = item[index];

    // Safely check if arg is null (reference types) or has no value (nullable value types)
    if (EqualityComparer<T>.Default.Equals(arg, default(T)))
    {
        return ConvertValue<T>(valueStr, effectiveType);
    }

    // For non-default arg, still convert based on target type
    return ConvertValue<T>(valueStr, effectiveType);
}

// Helper method to clean up conversion logic
private T ConvertValue<T>(string valueStr, Type effectiveType)
{
    if (effectiveType == typeof(int))
    {
        if (int.TryParse(valueStr, out int intVal))
            return (T)(object)intVal;
    }
    else if (effectiveType == typeof(string))
    {
        return (T)(object)valueStr;
    }
    else if (effectiveType == typeof(decimal))
    {
        if (decimal.TryParse(valueStr, out decimal decVal))
            return (T)(object)decVal;
    }

    // Return default if conversion fails or type isn't supported
    return default(T);
}

Key Improvements Explained

  • Target Type Detection: We use typeof(T) instead of arg.GetType() to avoid null reference issues, and Nullable.GetUnderlyingType to handle nullable value types (like int?) correctly.
  • Safe Null/Default Check: EqualityComparer<T>.Default.Equals(arg, default(T)) safely checks if arg is null (for reference types) or has no value (for nullable value types) without risking exceptions.
  • Robust Parsing: TryParse replaces Convert methods, so invalid strings won't crash the method—instead, it returns the default value for T.
  • Cleaner Logic: Extracting conversion to a helper method makes the code easier to read and maintain.

Testing Scenarios

  • When arg is string null: The method returns the raw string from item[index] instead of trying to convert it to int.
  • When arg is Nullable<int> null: It parses the string to int (if possible) and returns it as a Nullable<int>.
  • When conversion fails: Returns default(T) (e.g., null for string, 0 for int, null for int?).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:53:37