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