【问题标题】:Method that accepts only classes that implement a specific interface仅接受实现特定接口的类的方法
【发布时间】:2015-09-03 08:19:33
【问题描述】:

我有以下方法

    private void PushToMainWindow(UserControl child) // where child is IMainWindowPlugin
    {
        _navigationStack.Push((IMainWindowPlugin)child);
        ...
        // Here I do stuff that makes use of the child as a usercontrol
        child.Width = 500;
        child.Margin = new Thickness(0,0,0,0);
        ...
    }

我想做的是通知编译器我将只接受同样实现 IMainWindowPlugin 接口的 UserControl 对象。

我知道我可以执行 if 语句并抛出或强制转换并检查 null,但这些都是运行时解决方案,我正在寻找一种方法来预先告诉开发人员对他可以添加的 UserControl 类型。有没有办法在 c# 中这样说?

更新: 添加了更多代码以显示用户控件用作用户控件,因此我不能只将子作为接口传递。

【问题讨论】:

标签: c# wpf user-controls


【解决方案1】:

你考虑过泛型吗?这样的事情应该可以工作:

    private void PushToMainWindow<T>(T child) where T: UserControl, IMainWindowPlugin
    {
        var windowPlugin = child as IMainWindowPlugin;
        _navigationStack.Push(windowPlugin);
        ...
        // Here I do stuff that makes use of the child as a usercontrol
        child.Width = 500;
        child.Margin = new Thickness(0,0,0,0);
        ...
    }

编译器不允许将不符合where 子句的对象传递给PushToMainWindow() 方法,这意味着您要传递的类必须是UserControl(或派生的)并实现IMainWindowPlugin

另一件事是,可能传递接口本身是更好的主意,而不是基于具体的实现。

【讨论】:

  • 这确实是个不错的解决方案,系统会自动完成T
  • 泛型非常有用。参考MSDN深入话题:msdn.microsoft.com/en-us/library/…
  • 谢谢,我已经实现了这个解决方案,并且它的工作 100%
【解决方案2】:

为什么不

void PushToMainWindow(IMainWindowPlugin child) { ... }

【讨论】:

  • 好的,这很有道理,让我为问题添加更多细节
【解决方案3】:
 private void PushToMainWindow(IMainWindowPlugin child) 
    {
        _navigationStack.Push(child);
        var newChild=(UserControl )child
        newChild.Width = 500;
        newChild.Margin = new Thickness(0,0,0,0);
    }

【讨论】:

  • 它只是颠倒了问题,我希望两个条件都满足,谢谢!
猜你喜欢
  • 2019-04-07
  • 2017-05-29
  • 2011-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多