【问题标题】:Convert Null Value to String - C#.NET将 Null 值转换为字符串 - C#.NET
【发布时间】:2010-05-23 10:50:54
【问题描述】:
    foreach (PropertyInfo PropertyItem in this.GetType().GetProperties())
    {
        PropertyItem.SetValue(this, objDataTable.Rows[0][PropertyItem.Name.ToString()], null);
    }

在其中一个循环中,我得到了这个异常错误:

“System.DBNull”类型的对象无法转换为“System.String”类型。

发生错误是因为数据库中的某个字段没有值(null),因此字符串属性无法处理它。如何将此 null 转换为字符串?

I got this solution

如果您知道更短或更好的,请随时发布。我试图避免检查每个循环当前值是否为空。

【问题讨论】:

  • recent.item == null ? "~/Content/images/default.jpg" : 最近的.item;

标签: c# .net vb.net reflection


【解决方案1】:

Ben 几乎是对的(我实际上认为这只是他的“错字”,但我无法为他编辑)。这应该可以解决问题。

foreach (PropertyInfo PropertyItem in this.GetType().GetProperties())
    {
        var value = objDataTable.Rows[0][PropertyItem.Name.ToString()];
        PropertyItem.SetValue(this, value == DBNull.Value ? "" : value.ToString() , null);
    }

而且您需要在每次迭代中进行测试,因为它是给定行中给定单元格中的值,因此确实无法避免在使用这些单元格值之前检查它们中的每一个

【讨论】:

  • coalesce 操作员会不会把它缩短一点(value as string) ?? string.Empty(真正的问题我不知道答案)
  • 不幸的是,它不会严格用于空值,并且由于 DBNull.Value 是一个对象,它不会起作用。但这是一个很好的评论,我喜欢它
  • 由于 SO 错误而无法编辑帖子,所以改为发表评论。如果您只想使用空字符串,您可以在上面的示例 SetValue(this, value.ToString(),null) 中调用 .ToString() on value
【解决方案2】:

除了在存在取消引用或方法调用的情况下检查 null 之外,没有其他解决方案。

如果PropertyItem.Name 可以为空或PropertyItem.SetValue 不能接受空值,那么您必须检查每个循环。

【讨论】:

  • 这似乎不是问题 - DBNull.Value.ToString() 工作正常并返回一个空字符串。 Property.SetValue() 在尝试将字符串类型的属性设置为 DBNull.Value 时会导致异常。检查应该是 objDataTable.Rows[0][PropertyItem.Name.ToString()] == DBNull.Value。
  • @Daniel - 我以 PropertyItem.Name 为空为例。我会更正答案
【解决方案3】:
foreach (PropertyInfo PropertyItem in this.GetType().GetProperties())
    {
        string strValue = objDataTable.Rows[0][PropertyItem.Name.ToString()] == DbNull.Value ? String.Empty : objDataTable.Rows[0][PropertyItem.Name.ToString()].ToString();
        PropertyItem.SetValue(this, strValue, null);
    }

【讨论】:

  • 我认为是objDataTable.Rows[0][strValue]DbNull 而不是PropertyItem.Name
  • 我已经在此基础上更新了我的答案。不过,这有点小技巧,将其封装在一个方法中会更好。
  • 希望我是对的! PropertyItem.Name 是面向反射而不是面向 DB,所以如果它使用 DbNull.Value 而不仅仅是 null,我会感到惊讶。
  • 爱上 ??操作员并将那个东西切成 1/2
  • @Martin 我很漂亮,你是对的。 PropertyInfo.Name 永远不会返回 DBNull.Value。
猜你喜欢
  • 2010-11-22
  • 2010-12-15
  • 1970-01-01
  • 2012-04-12
  • 1970-01-01
  • 2022-10-01
  • 2016-01-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多