ExpandoObjects 的动态视图“隐藏”具有空值的属性

Tim*_*out 5 c# dynamic expandoobject

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

我知道我可以通过直接使用 ExpandoObject、添加一堆尝试捕获、将 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);
Run Code Online (Sandbox Code Playgroud)

jbt*_*ule 3

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

string someString2 = string.Format("{0}", (object)dynamicRef.NulledProperty);
Run Code Online (Sandbox Code Playgroud)