gpt4 book ai didi

C# - 使用反射的动态转换

转载 作者:太空宇宙 更新时间:2023-11-03 20:32:33 24 4
gpt4 key购买 nike

我正在尝试从数据表对象中提取值并动态填充对象以进行 web 服务调用,我尝试了一些方法但将它们缩小到这个范围,它似乎缺少反射(reflect)目标类型的能力并将数据表中的对象转换为一个。

我在这里挠头了很多!

foreach (PropertyInfo pi in zAccount)
{
object o = row[pi.Name];
if (o.GetType() != typeof(DBNull))
{
pi.SetValue(a, o, null);
}
}

这给我类型转换错误:

“System.String”类型的对象无法转换为“System.Nullable`1[System.Boolean]”类型。

所以理想的情况应该是这样的:

foreach (PropertyInfo pi in zAccount)
{
object o = typeof(pi.GetType())row[pi.Name];
pi.SetValue(a, o, null);
}

最佳答案

这是一段代码,我用它来做你想做的事情;从数据库中转换类型。通常您可以使用 Convert.ChangeType,但这不适用于可空类型,因此此方法可以处理这种情况。

/// <summary>
/// This wrapper around Convert.ChangeType was done to handle nullable types.
/// See original authors work here: http://aspalliance.com/852
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="conversionType">The type to convert to.</param>
/// <returns></returns>
public static object ChangeType(object value, Type conversionType)
{
if (conversionType == null)
{
throw new ArgumentNullException("conversionType");
}
if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
if (value == null)
{
return null;
}
NullableConverter nullableConverter = new NullableConverter(conversionType);
conversionType = nullableConverter.UnderlyingType;
}
return Convert.ChangeType(value, conversionType);
}

然后您可以像这样使用它:

foreach (PropertyInfo pi in zAccount)
{
object o = ChangeType(row[pi.Name], pi.GetType());
pi.SetValue(a, o, null);
}

编辑:

实际上,重新阅读你的帖子,你的错误信息

Object of type 'System.String' cannot be converted to type 'System.Nullable`1[System.Boolean]'.

让它看起来像你从数据库中得到的类型是一个string,但是属性是bool?类型(可为空 bool 值)因此它不能'不要转换它。

关于C# - 使用反射的动态转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6736665/

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