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

Mik*_*keW 8 c#

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

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

Cht*_*lek 5

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

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

然后..

if (doesPropertyExist(myDynamicObject, "myProperty")){
    // ...
}
Run Code Online (Sandbox Code Playgroud)

  • ((Type)obj.GetType()).GetProperties().Any(p => p.Name.Equals(property)); (2认同)

123*_*9 0 0

您需要用 try catch 包围动态变量,没有其他方法可以使其安全。

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

  • 不好了!您尝试在逻辑中使用异常,而只需要检查列表中的属性(转换为 ExpandoObject 或使用反射)。相反,您称之为核弹 - 原因和句柄异常。 (2认同)