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

Mat*_*att 1 c# reflection casting visual-studio

我试图从数据表对象中提取值并动态填充对象以进行webservice调用,我已经尝试了一些方法但是将它们缩小到这个,它似乎缺少的是能够反映目标类型并转换为对象从数据表变为一个.

我在这里摸不着头脑!

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

这给了我类型转换错误:

"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);
                 }
Run Code Online (Sandbox Code Playgroud)

Cod*_*ike 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);
}
Run Code Online (Sandbox Code Playgroud)

然后你会像以下一样使用它:

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

编辑:

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

"System.String"类型的对象无法转换为"System.Nullable .1 [System.Boolean]"类型.

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