gpt4 book ai didi

c# - 类型为 'System.Int16' 的对象无法转换为类型 'System.Nullable` 1[System.Int32]

转载 作者:行者123 更新时间:2023-12-05 02:15:58 32 4
gpt4 key购买 nike

我有一个方法可以从数据读取器的数据中生成类类型列表。

if (datareader != null && datareader .HasRows)
{
Dictionary<string, PropertyInfo> pDict= GetPropertyDictionary<T>();
var fields = GetFieldNames(datareader );
while (datareader .Read())
{
T myobj= new T();
for (int index = 0; index < fields.Count; index++)
{
if (pDict.TryGetValue(fields[index], out PropertyInfo info))
{
var val1 = datareader .GetValue(index);
info.SetValue(myobj, (val1 == DBNull.Value) ? null : val1, null);
}
}
}
}

我有类属性,其中一些可以为空。

public string StudentName{ get; set; }
public decimal? percentage{ get; set; }
public int? StudentNumber{ get; set; }

代码适用于所有属性,除了 StudentNumber 是 int。

在上面的代码中,以下行抛出异常 Object of type 'System.Int16' cannot be converted to type 'System.Nullable`1[System.Int32] :

info.SetValue(myobj, (val1 == DBNull.Value) ? null : val1, null);

如何解决这个问题?

最佳答案

你在这里遇到的问题是,虽然你可以使用 shortint , 你不能投一个盒装的 shortint直接地。即,

object box = (short)5;
var x = (int?)box; // Invalid cast.
var y = (int?)(short?)box; // fine, we cast to short and then to int.

您可以将类的属性类型更改为 short? ,或者您可以检查您的属性的类型是否为 Nullable<int32>并使用 Convert.ToInt32在那种情况下的值(value)。

关于c# - 类型为 'System.Int16' 的对象无法转换为类型 'System.Nullable` 1[System.Int32],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50842262/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com