c# - “ExpandoObject”不包含 'PropertyChanged' 的定义

标签 c# dynamic interface expandoobject impromptu-interface

我正在尝试使用ImpromptuInterface来解决我在这里遇到的问题。 Adding Interface Implementation to ExpandoObject .

我现在可以在基类中访问接口(interface)的各种属性,但无法再订阅 ExpandoObject 的 PropertyChanged 事件。

在进行故障排除时,我能够简化问题,如图所示。

Service.cs

using ImpromptuInterface;

public Service()
{
    InitializeComponent();

    dynamic expando = new ExpandoObject();

    try
    {
        INotifyPropertyChanged obj = Impromptu.ActLike(expando);

        obj.PropertyChanged += obj_PropertyChanged;
    }
    catch (Exception ex)
    {
        EventLog.WriteEntry(ex.ToString(), EventLogEntryType.Error);
    }

    try
    {
        INotifyPropertyChanged obj = Impromptu.ActLike<INotifyPropertyChanged>(expando);

        obj.PropertyChanged += obj_PropertyChanged;
    }
    catch (Exception ex)
    {
        EventLog.WriteEntry(ex.ToString(), EventLogEntryType.Error);
    }
}

private void obj_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    throw new NotImplementedException();
}

我收到一条错误消息

'System.Dynamic.ExpandoObject' does not contain a definition for 'PropertyChanged'

每次我尝试在构造函数中连接事件处理程序时都会发生这种情况。

事件日志 1

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'System.Dynamic.ExpandoObject' does not contain a definition for 'PropertyChanged'
   at CallSite.Target(Closure , CallSite , Object )
   at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
   at ActLike_INotifyPropertyChanged_dc51b6c65bf147d0b5f35218102e3c11.add_PropertyChanged(PropertyChangedEventHandler value)
   at Service..ctor()

事件日志2

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'System.Dynamic.ExpandoObject' does not contain a definition for 'PropertyChanged'
   at CallSite.Target(Closure , CallSite , Object )
   at ActLike_INotifyPropertyChanged_dc51b6c65bf147d0b5f35218102e3c11.add_PropertyChanged(PropertyChangedEventHandler value)
   at Service..ctor()

我不能这样使用ImpromptuInterface吗?

最佳答案

问题源于以下事实:ImpromptuInterface 使用 DLR,而 DLR 无法处理显式接口(interface)调用,而这正是它在 Expando 上实现的方式。通过让代理检查其目标是否实现即兴包装的确切接口(interface),可以一般性地修复它。我得再考虑一下。用这个跟踪issue .

作为解决此特定问题的方法,Dynamitey.Dynamic.Dictionary : BaseDictionary工作方式与 Expando 类似,并且具有 PropertyChanged 作为普通事件属性。

关于c# - “ExpandoObject”不包含 'PropertyChanged' 的定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41367074/

相关文章:

javascript - 无法从 JavaScript 中动态创建的文本字段获取数据

python - 动态添加项目到 Tkinter Canvas

java - Spring in Action 第 4 版中 JPA 存储库示例的问题

c# - 为什么 DateTime.ToDateTime( ) 不能编译?

c# - 如何在运行时创建 WPF UserControl 的图像

c# - 首次创建序列化类时的默认条目

C#:如何从对象变量中的值和类型变量中的类型获取类型变量?

php - 来自动态函数名称的 Javascript 新对象实例

c# - Windows XP 上 WPD/WIA 的替代方案?

c++ - 如何读取 Linux 网络接口(interface)文件 (/etc/network/interfaces) 上的参数