我有以下方法
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 接口(interface)的 UserControl 对象。
我知道我可以执行 if 语句并抛出或强制转换并检查是否为 null,但这些都是运行时解决方案,我正在寻找一种方法来预先告诉开发人员存在对 null 的限制他可以添加的 UserControl 类型。有没有办法在 C# 中这样说?
更新: 添加了更多代码以显示 usercontrol 用作 usercontrol,因此我不能只将 child 作为接口(interface)传递。
最佳答案
您是否考虑过泛型?这样的事情应该有效:
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
。
另一件事是,可能传递接口(interface)本身是更好的主意,而不是基于具体实现。
关于c# - 只接受实现特定接口(interface)的类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32370460/