![](/img/trans.png)
[英]Expression of type 'System.Nullable`1[System.Int32]' cannot be used for constructor parameter of type 'System.Int32'\r\nParameter name: arguments[0]
[英]Object of type 'System.Int16' cannot be converted to type 'System.Nullable`1[System.Int32]
我有一種從數據讀取器的數據生成類類型列表的方法。
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除外。
在上面的代碼中,以下行引發'System.Int16'類型的對象對象不能轉換為'System.Nullable`1 [System.Int32]類型 :
info.SetValue(myobj,(val1 == DBNull.Value)?null:val1,null);
如何解決這個問題?
我出於很多原因不同意此代碼,但是為了解決您當前的問題並回答您的問題,這是因為您無法將Int16
顯式轉換為Int32
或Nullable<Int32>
或int?
。
為此,您需要先將值轉換為Int32
然后轉換為Nullable<Int3>
。
有更好的方法可以讓您弄清楚發生了什么並在此處修復此錯誤...
info.SetValue(myobj, val1 == DBNull.Value ? null : (int?)Convert.ToInt32(val1), null);
您在這里遇到的問題是,盡管您可以將short
轉換為int
,但是不能直接將boxed short
強制轉換為int
。 即
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
。
嘗試更改類型:
var val1 = datareader.GetValue(index);
var convertedValue = (val1 == DBNull.Value) ? null : Convert.ChangeType(val1, info.PropertyType);
info.SetValue(myobj, convertedValue, null);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.