[英]A first chance exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred
[英]Accessing a dynamic's property threw an exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException'
我将处理程序函数作为参数传递给另一个函数。 处理程序的参数之一是动态对象,我正在访问其属性之一。
下面是一个例子:
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
的定义。
我查看了这些答案以寻求解决方案:
为什么动态对象的赋值会抛出 RuntimeBinderException?
在私有类型上动态抛出 Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
和以下作品:
Dictionary<string, object> values = ((object)timed)
.GetType()
.GetProperties()
.ToDictionary(p => p.Name, p => p.GetValue(v));
( 获取动态类型的属性)
但我不确定为什么直接访问停止工作。 有任何想法吗? 谢谢!
我发现了它破裂的原因。 最初,处理程序和处理程序传入的函数都属于同一个程序集。 重构处理程序后,调用它的对象被拆分为不同的项目和命名空间,从而防止在编译时进行绑定。
解决方案是不再传递动态而是序列化对象:
OnTime?.Invoke(JsonConvert.SerializeObject(new { name = dto.Name, dto, request }), httpResponseMessage, elapsed);
然后将其消耗为:
protected virtual void OnTime(string timed, HttpResponseMessage response, TimeSpan time)
{
var operation = JsonConvert.DeserializeAnonymousType(timed, new { name = string.Empty });
_logger.Write(operation.name);
}
因此,解耦需要额外的序列化步骤,但允许更多地重用代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.