如何将字符串值内容转换为泛型`int?` (nullable int)?

问题描述 投票:0回答:0

具有通用输出类型的方法,我需要将字符串值(在方法内部读取)转换为给定类型

T
,该类型也可以为空。简化的方法代码如下所示:

    public T ReadN<T>()
    {
        string valueStr = "000004346"; // actually read from a file

        // When it should be converted to null for nullable types,
        // return the default (that is null).
        if (Nullable.GetUnderlyingType(typeof(T)) != null 
            && Nullable.GetUnderlyingType(typeof(T)) != typeof(string)
            && valueStr.Trim() == "")
            return default;

        // Being here, I know it can be converted to the non-null value.
        return (T)Convert.ChangeType(valueStr, typeof(T));
    }

调用方法时:

    int? result = ReadN<int?>();

我得到例外:

System.InvalidCastException
  HResult=0x80004002
  Message=Invalid cast from 'System.String' to 'System.Nullable`1[[System.Int32, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]'.
  Source=System.Private.CoreLib

应该如何正确完成

string
int?
(作为通用
T
传递)的转换?

c# nullable data-conversion
© www.soinside.com 2019 - 2024. All rights reserved.