【问题标题】:Impleneting general function for generic interface实现通用接口的通用功能
【发布时间】:2011-07-25 17:05:20
【问题描述】:

编辑 示例中的属性名称输入错误

假设我们有这样的接口

public interface IBase {}
public interface IItf_1: IBase {}
public interface IItf_2: IBase {}
public interface IItf_3: IBase {}

public interface IInterfaceHolder<T>: IBase, INotifyPropertyChanged {
  // Changes to this property caused raise of the PropertyChanged event
  bool Checked { get; set; }
  T Item { get; }
}

public interface ISomeFunnyInterface: INotifyPropertyChanged {
  IEnumerable<IInterfaceHolder<IItf_1>> Collection_1 { get; }
  IEnumerable<IInterfaceHolder<IItf_2>> Collection_2 { get; }
  IEnumerable<IInterfaceHolder<IItf_3>> Collection_3 { get; }
}

这个想法是将 PropertyChanged 从每个 Checked 属性传输到从 ISomeFunnyInterface 引发的 PropertyChaned,并具有相应的属性名称(不是“Checked”)。

显而易见的解决方案是通过接口 IInterfaceHolder 处理每个 PropertyChanged 发送。但问题是当我编写处理程序时:

private void GenericSelectorSelected_PropertyChanged(object sender, PropertyChangedEventArgs e) {
    dynamic el = (dynamic)sender;

    // here an exception is thrown, because sender (or more correctly 'el') is
    // handled as IBase, and not as IInterfaceHolder
    if (el.Checked) {
    }
    else {
    }
}

如何解决这个问题?如何使其工作而不需要为每个 IInterfaceHandler<.>

编写单独的处理程序

【问题讨论】:

    标签: c#-4.0 interface generics


    【解决方案1】:

    如果您只想要一个通用接口实现而不是您正在做的事情,您可以使用ImpromptuInterface(可通过 nuget 获得)。它允许你继承一个 DynamicObject,然后给它一个静态接口。

    IItf_1 test1 = Impromptu.ActLike<IItf_1>(myDynamicObject);
    

    【讨论】:

      猜你喜欢
      • 2022-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-18
      • 2010-12-18
      • 2023-03-07
      相关资源
      最近更新 更多