繁体   English   中英

C# - 使用反射的动态投射

[英]C# - Dynamic casting using reflection

我正在尝试从数据表 object 中提取值并动态填充 object 以进行 Web 服务调用,我尝试了一些方法,但将它们缩小到这一点,它似乎缺少反映目标类型和强制转换的能力object 从数据表中合二为一。

我在这里经常挠头!

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

这给了我类型转换错误:

“System.String”类型的 Object 无法转换为“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);
}

编辑:

实际上,重新阅读您的帖子,您的错误消息

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

使它看起来像您从数据库返回的类型是string ,但属性是bool? (可为空的布尔值)因此它无法转换它。

只是猜测,但可能是你的 o 是一个字符串(如“false”),你的属性可能是 bool,因此是错误。

您可以使用 Convert.ChangeType。 它可能会有所帮助

这是因为您的行包含类型与帐户 class 的属性类型不匹配的数据。

为什么会这样,如果没有看到您的更多代码,我不知道。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM