仅接受实现特定接口的 类 的方法
Method that accepts only classes that implement a specific interface
我有以下方法
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,所以我不能只将 child 作为接口传递。
为什么不
void PushToMainWindow(IMainWindowPlugin child) { ... }
private void PushToMainWindow(IMainWindowPlugin child)
{
_navigationStack.Push(child);
var newChild=(UserControl )child
newChild.Width = 500;
newChild.Margin = new Thickness(0,0,0,0);
}
你考虑过泛型吗?这样的事情应该有效:
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()
方法,这意味着您传递的 class 必须是 UserControl
(或派生)并实施 IMainWindowPlugin
。
另一件事是,可能传递接口本身是更好的主意,而不是基于具体实现。
我有以下方法
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,所以我不能只将 child 作为接口传递。
为什么不
void PushToMainWindow(IMainWindowPlugin child) { ... }
private void PushToMainWindow(IMainWindowPlugin child)
{
_navigationStack.Push(child);
var newChild=(UserControl )child
newChild.Width = 500;
newChild.Margin = new Thickness(0,0,0,0);
}
你考虑过泛型吗?这样的事情应该有效:
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()
方法,这意味着您传递的 class 必须是 UserControl
(或派生)并实施 IMainWindowPlugin
。
另一件事是,可能传递接口本身是更好的主意,而不是基于具体实现。