【问题标题】:How to safely check if a dynamic object has a field or not如何安全地检查动态对象是否具有字段
【发布时间】:2013-06-30 15:02:53
【问题描述】:

我正在遍历动态对象的属性以查找字段,但我无法弄清楚如何在不引发异常的情况下安全地评估它是否存在。

        foreach (dynamic item in routes_list["mychoices"])
        {
            // these fields may or may not exist
           int strProductId = item["selectedProductId"];
           string strProductId = item["selectedProductCode"];
        }

【问题讨论】:

标签: c#


【解决方案1】:

使用反射比 try-catch 更好,所以这是我使用的函数:

public static bool doesPropertyExist(dynamic obj, string property)
{
    return ((Type)obj.GetType()).GetProperties().Where(p => p.Name.Equals(property)).Any();
}

那么..

if (doesPropertyExist(myDynamicObject, "myProperty")){
    // ...
}

【讨论】:

  • ((Type)obj.GetType()).GetProperties().Any(p => p.Name.Equals(property));
  • ((Type)obj.GetType()).GetProperties() 没有得到任何属性,即使我可以看到有属性
【解决方案2】:

这很简单。设置一个检查值为 null 或空的条件。如果该值存在,则将该值分配给相应的数据类型。

foreach (dynamic item in routes_list["mychoices"])
        {
            // these fields may or may not exist

            if (item["selectedProductId"] != "")
            {
                int strProductId = item["selectedProductId"];
            }

            if (item["selectedProductCode"] != null && item["selectedProductCode"] != "")
            {
                string strProductId = item["selectedProductCode"];
            }
        }

【讨论】:

  • 您在两个if 语句中检查selectedProductId
  • 动态对象中可能缺少属性本身,而不是值 - 所以标准的空检查会引发调用异常 - 虽然 try{}catch{} 似乎可以完成这项工作
【解决方案3】:

你需要用 try catch 包围你的动态变量,没有其他更好的方法来保证它的安全。

try
{
    dynamic testData = ReturnDynamic();
    var name = testData.Name;
    // do more stuff
}
catch (RuntimeBinderException)
{
    //  MyProperty doesn't exist
} 

【讨论】:

  • 哦不!您尝试在逻辑中使用异常,而只需要在列表中检查您的属性(转换为 ExpandoObject 或使用反射)。取而代之的是,您将其称为核弹 - 原因和句柄异常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-12
  • 2015-09-03
  • 1970-01-01
  • 1970-01-01
  • 2016-07-10
  • 2011-11-10
  • 2019-07-01
相关资源
最近更新 更多