在 foreach 动态调用中捕获 RuntimeBinderException

Catching RuntimeBinderException in foreach dynamic calls

我有一些代码将 JSON 读入动态对象,如下所示:

dynamic listOfThings = JsonConvert.DeserializeObject(listOfThingsJson);

我像这样遍历它们:

foreach(dynamic thing in listOfThings) {
    string propertyOne = thing.PropertyOne;
    string propertyTwo = thing.PropertyTwo;
    doWork(propertyOne, propertyTwo);
}

如果我在 foreach 语句本身或任一 属性 访问语句中遇到 RuntimeBinderException,我该如何捕获,但只是忽略该迭代的执行并继续循环?

类似于:

foreach(dynamic thing in listOfThings) { \if a RuntimeBinderException is thrown on this line
    string propertyOne = thing.PropertyOne \or on this line
    string propertyTwo = thing.PropertyTwo \or on this line, catch the exception
    doWork(propertyOne, propertyTwo)      \and move to the next iteration

不知道为什么你不能使用像

这样的try .. catch
foreach(dynamic thing in listOfThings) {
try {
    string propertyOne = thing.PropertyOne;
    string propertyTwo = thing.PropertyTwo;
    doWork(propertyOne, propertyTwo);
}
catch(RuntimeBinderException ex)
{
  //log the exception
  continue;
}
}