【问题标题】:Unable to ChangeType from string to int? [duplicate]无法将类型从字符串更改为整数? [复制]
【发布时间】:2023-03-16 09:30:01
【问题描述】:

在我们的应用程序的深处,尝试使用Convert.ChangeType(value, castType) 执行从字符串到可为空的int 的转换。在这种情况下,值如下:

value: "00010"
castType: Nullable<System.Int16>

问题是我收到以下错误

Invalid cast from 'System.String' to 'System.Nullable`1[[System.Int16}

我(显然错误地)认为这类似于强制转换或 Convert.ToInt16(),但我通过测试以下两行代码验证了它不一样。

Int16 t = Convert.ToInt16("00010");
object w = Convert.ChangeType("00010", typeof(short?));

您可能会怀疑,第一个成功,而第二个失败并显示上述错误消息。

是否可以通过调整以这种方式使用 ChangeType,或者我应该看看重构?

【问题讨论】:

  • 我最终根据链接中的信息这样做了:Convert.ChangeType(value, Nullable.GetUnderlyingType(castType) ?? castType);

标签: c# .net casting type-conversion


【解决方案1】:

你需要这样写:

var value = "00010";
short? w = value == null ? null : (short?)Convert.ChangeType("00010", typeof(short));

ChangeType 不适用于 Nullable&lt;T&gt; - 如果我们有 value 的值,我们假设我们有一个转换后类型的值

【讨论】:

  • 这很有价值,但我的类型值是在运行时使用typeof(T).GetProperty().PropertyType 设置的,所以我不确定是否可以进行显式转换
【解决方案2】:

根据Convert.ChangeType

ChangeType(Object, Type) 方法可以将一个可为空的类型转换为另一种类型。但是,它不能将其他类型转换为可空类型的值,即使 conversionTypeNullable&lt;T&gt; 的基础类型。 要执行转换,您可以使用强制转换运算符(在 C# 中)或转换函数(在 Visual Basic 中)。

那么,试试吧:

var w = (short?)Convert.ChangeType("00010", typeof(short));

【讨论】:

  • 我完全错过了粗体部分。感谢您指出这一点。
猜你喜欢
  • 2015-08-02
  • 2023-03-20
  • 2021-08-26
  • 1970-01-01
  • 1970-01-01
  • 2018-03-21
  • 1970-01-01
  • 1970-01-01
  • 2020-11-10
相关资源
最近更新 更多