gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:44:09 27 4
gpt4 key购买 nike

我正在遍历动态对象的一个​​属性来寻找一个字段,但我不知道如何在不抛出异常的情况下安全地评估它是否存在。

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

最佳答案

使用反射比 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")){
// ...
}

关于c# - 如何安全地检查动态对象是否有字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17439248/

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