C# - 使用反射进行动态投射

时间:2011-07-18 17:17:09

标签: c# visual-studio reflection casting

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

我在这里摸不着头脑!

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);
                 }

3 个答案:

答案 0 :(得分:5)

这是我用来完成你想要做的事情的一段代码;将类型转换为DB。通常你可以使用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'类型的对象无法转换为'System.Nullable`1 [System.Boolean]'类型。

使得从数据库中获取的类型看起来像string,但属性类型为bool?(可以为空的布尔值),因此无法转换它。

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

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

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