[英]How to assign null values to dynamic property type
Basically, I am in need of a converter which converts a DataReader
object to generic type. 基本上,我需要一个将
DataReader
对象转换为通用类型的转换器。
so when I do - 所以当我做的时候-
while(dataReader.HasRows()){
var result= dataReader.ConvertToObject<MyModel>();
}
It calls an extension method of generic type - 它调用通用类型的扩展方法-
public static T ConvertToObject<T>(this DbDataReader reader) where T : new()
{
T res = new T();
T t = new T();
for (int inc = 0; inc < reader.FieldCount; inc++)
{
Type type = t.GetType();
PropertyInfo prop = type.GetProperty(reader.GetName(inc));
var value = reader.GetValue(inc);
if (value == System.DBNull.Value)
{
value = null;
}
var targetType = IsNullableType(prop.PropertyType) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType;
value = Convert.ChangeType(value, targetType);
prop.SetValue(t, value, null);
}
res = t;
return res;
}
private static bool IsNullableType(Type type)
{
return type.IsConstructedGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>));
}
It works fine until the the result in datareader
is System.DBNull
except the System.String
正常工作,直到
datareader
的结果为System.DBNull
为止,除了System.String
To handle null values I forcefully checked if the value is type of System.DBNull
then assign it a C# NULL
object. 为了处理空值,我强制检查了该值是否为
System.DBNull
类型,然后为其分配了一个C# NULL
对象。
if (value == System.DBNull.Value)
{
value = null;
}
This however fails the conversion when the result is null for numeric type object. 但是,当数字类型对象的结果为null时,转换将失败。
So basically I am trying to do is when the result value is type - System.Nullable[System.Decimal]
所以基本上我想做的是当结果值为类型时
System.Nullable[System.Decimal]
then 然后
if (value == System.DBNull.Value)
{
value = (System.Decimal?) null;
}
Or 要么
value = (System.DateTime?)null //for DateTime
value = (System.Int32?)null //for Int32
What I tried to get dynamic property type 我试图获取动态属性类型的内容
if (value == System.DBNull.Value)
{
value = (prop.PropertyType ?) null; // to get it dynamic
}
This didn't work. 这没用。 Please let me know what I have to do?
请让我知道我该怎么办?
You can't specify null
as a value of type T
because it might not be a valid value for T
. 您不能将
null
指定为T
类型的值,因为它可能不是T
的有效值。 (Think int
etc.) (请考虑
int
等)
However, you can use default(T)
, which will be the default value for T
- the same value you'd get if you left a field of type T
uninitialized, for example. 但是,您可以使用
default(T)
,它将是T
的默认值-例如,如果您将T
类型的字段保留为未初始化,则将获得相同的值。 That will be: 那将是:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.