gpt4 book ai didi

c# - 具有空值的 ExpandoObjects "hides"属性的动态 View

转载 作者:行者123 更新时间:2023-11-30 12:14:24 24 4
gpt4 key购买 nike

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

最佳答案

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

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

关于c# - 具有空值的 ExpandoObjects "hides"属性的动态 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9588565/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com