C# 方法,该方法只接受实现特定接口的类

C# 方法,该方法只接受实现特定接口的类,c#,wpf,user-controls,C#,Wpf,User Controls,我有以下方法 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

我有以下方法

    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#来表达这一点

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

为什么不呢

void PushToMainWindow(IMainWindowPlugin child) { ... }

你考虑过泛型吗?像这样的方法应该会奏效:

    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);
        ...
    }
private void PushToMainWindow(T child),其中T:UserControl,IMainWindowPlugin
{
var windowPlugin=作为IMainWindowPlugin的子级;
_navigationStack.Push(windowPlugin);
...
//在这里,我做了一些事情,利用子控件作为用户控件
宽度=500;
边缘=新厚度(0,0,0,0);
...
}
编译器将不允许传递到不符合
where
子句的
PushToMainWindow()
方法对象,这意味着要传递的类必须是
UserControl
(或派生的)并实现
IMainWindowPlugin


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

好的,这很有意义,让我为这个问题添加更多细节。如果IMainWindowPlugin是您的接口,那么您可以创建从UserControl继承的基类,并且该接口的实现为空。还要检查一下这个:这看起来真的是一个很好的解决方案,系统自动完成TG,通用性非常有用。请参阅MSDN以深入了解该主题:谢谢,我已经实现了此解决方案,并且它100%工作。它只是反转了问题,我希望这两个条件都满足,谢谢!
    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);
        ...
    }