【发布时间】:2020-11-16 19:29:15
【问题描述】:
我将一个处理函数作为参数传递给另一个函数。处理程序的参数之一是一个动态对象,我正在访问它的一个属性。
这是一个例子:
protected virtual void OnTime(dynamic timed, HttpResponseMessage response, TimeSpan time)
{
_logger.Write(timed?.name);
}
下面是调用处理程序的方式:
OnTime?.Invoke(new {name = dto.name, dto, request }, httpResponseMessage, elapsed);
这很好。然后我洗了一些东西,它坏了。动态对象的所有属性都按预期出现,但现在 timed?.name 抛出 Microsoft.CSharp.RuntimeBinder.RuntimeBinderException 异常,抱怨该对象没有属性 name 的定义。
我查看了这些答案以寻求解决方案:
Why does the assignment from a dynamic object throw a RuntimeBinderException?
Dynamic throwing Microsoft.CSharp.RuntimeBinder.RuntimeBinderException on private types
以下作品:
Dictionary<string, object> values = ((object)timed)
.GetType()
.GetProperties()
.ToDictionary(p => p.Name, p => p.GetValue(v));
(Get properties of a Dynamic Type)
但我不确定为什么直接访问停止工作。有任何想法吗?谢谢!
【问题讨论】: