【问题标题】:Dynamic View of ExpandoObjects "hides" Properties with null ValuesExpandoObjects 的动态视图“隐藏”具有空值的属性
【发布时间】:2012-03-06 17:16:15
【问题描述】:

我有一些代码适用于由数据库调用填充的 ExpandoObjects。总是有些值是空值。当我将对象视为 ExpandoObject 时,我会看到底层字典中的所有键和值(包括空值)。但是,如果我尝试通过动态引用访问它们,则任何具有相应空值的键都不会显示在对象的动态视图中。当我尝试通过动态引用上的属性语法访问它时,我得到一个 ArgumentNullException。

我知道我可以通过直接使用 ExpandoObject、添加一堆 try catch、将 expando 映射到具体类型等来解决这个问题,但这违背了首先使用这个动态对象的目的地方。如果某些属性具有空值,则使用动态对象的代码可以正常工作。有没有更优雅或更简洁的方式来“取消隐藏”这些具有空值的动态属性?

这是演示我的“问题”的代码

dynamic dynamicRef = new ExpandoObject();
ExpandoObject expandoRef = dynamicRef;

dynamicRef.SimpleProperty = "SomeString";
dynamicRef.NulledProperty = null;

string someString1 = string.Format("{0}", dynamicRef.SimpleProperty);

// My bad; this throws because the value is actually null, not because it isn't
// present.  Set a breakppoint and look at the quickwatch on the dynamicRef vs.
// the expandoRef to see why I let myself be led astray.  NulledProperty does not
// show up in the Dynamic View of the dynamicRef
string someString2 = string.Format("{0}", dynamicRef.NulledProperty);

【问题讨论】:

  • ExpandoObject 可以存储 null 值,并将它们拉出来,你确定是什么导致了参数 null 异常吗?
  • 如果密钥存在于ExpandoObject 中,无论是否为null,它都会返回它。如果它不存在,它会抛出一个RuntimeBinderException。它不会抛出ArgumentNullException,所以你的代码中一定有一些错误。你能告诉我们抛出的代码吗?
  • 好的,我想我只是被 Visual Studio 监视窗口愚弄了。代码抛出 ArgumentNullException 是因为该值实际上为 null,而不是因为该属性“缺失”。当我在动态引用上设置监视时,如果它具有空值,它不会显示该属性。如果我把一个手表手表 ExpandoObject 引用到同一个对象,它会在底层键列表中显示属性名称。

标签: c# dynamic expandoobject


【解决方案1】:

您遇到的问题是动态运行时重载调用选择string .Format(format, params object[] args) 而不是预期的string.Format(string format, object arg0) 一个简单的转换将切换到string.Format 的静态调用并修复它。

string someString2 = string.Format("{0}", (object)dynamicRef.NulledProperty);

【讨论】:

  • 完美!这样就解决了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-09
  • 2021-10-16
  • 2017-04-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多