我正在寻找一个字段的动态对象上的一个属性循环,除了我无法弄清楚如何在不抛出异常的情况下安全地评估它是否存在.
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)
使用反射比 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)
您需要用 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)
| 归档时间: |
|
| 查看次数: |
8093 次 |
| 最近记录: |