情況:
資料表的 [生產日期、序號] 資料型態,可為NULL,並且長度不可為零
public class tblO統計資料表
{
public string 統計別 { get; set; }
public DateTime? 生產日期 { get; set; }
public int? 序號 { get; set; }
public string 卡號 { get; set; }
}
解決:
透過 IsGenericType 、 GetGenericTypeDefinition
判斷是否為 Nullable 的泛型
而決定INSERT時,值要放 Null 還是 EmptyString/String
C#
If (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
var t = typeof(tblO統計資料);
var PropertyInfos = t.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var PropertyInfoItem in PropertyInfos)
{
var vv = PropertyInfoItem.PropertyType.IsGenericType && PropertyInfoItem.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>);
}
VB.NET
If type.IsGenericType AndAlso type.GetGenericTypeDefinition() Is GetType(Nullable(Of)) Then
-------------------------------------------------------------------------------------
Dim mdl = Assembly.LoadFile(HttpContext.Current.Server.MapPath("~/bin/" & modelName)).GetType(modelClsName)
For Each v In mdl.GetProperties()
If v.PropertyType.IsGenericType() AndAlso v.PropertyType.GetGenericTypeDefinition() Is GetType(Nullable(Of )) Then
args.Add("@" & rw.Key, IIf(Not String.IsNullOrEmpty(rw.Value), rw.Value.ToString(), Nothing))
Else
args.Add("@" & rw.Key, rw.Value.ToString())
End If
Next
參考:
C# Reflection: How to get the type of a Nullable<int>?
Difference between IsGenericType and IsGenericTypeDefinition
Type中的3个bool属性: IsGenericType , IsGenericTypeDefinition , IsGenericParameter
使用反射(Reflection)對物件的結構進行操作 (一)