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

标签 c# visual-studio reflection casting

我正在尝试从数据表对象中提取值并动态填充对象以进行 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/

相关文章:

c# - 如何在 Entity Framework 中选择多个列?

c# - 参数名前面的@有什么作用?

c++ - 如何忽略 LNK2038(定义不匹配)?

visual-studio - 是否可以从 Visual Studio 调试 QML?

java - 无法通过反射 getter 获取字段值

java - 在界面上查找注释

c# - 在变化的位置插入琴弦

c# - Tridion 2011 核心服务 : Unable to update component with new field using Xml manipulation

go - 将映射序列化到 gob 后 DeepEqual 不正确

c# - 使用html将文档存储到Elastic Search