如何安全地检查动态对象是否有字段

时间:2013-07-03 03:38:41

标签: c#

我正在寻找一个字段的动态对象上的一个属性循环,除了我无法弄清楚如何在不抛出异常的情况下安全地评估它是否存在。

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

3 个答案:

答案 0 :(得分:1)

您需要使用try catch来包围您的动态变量,没有其他方法可以更好地保护它。

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

答案 1 :(得分: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")){
    // ...
}

答案 2 :(得分:0)

这很简单。设置一个检查值为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"];
            }
        }