在 C# 中,可以定义具有两个接口(interface)限制的方法参数。这有界限。例如。
interface IA
{
int A {get;}
}
interface IB
{
int B {get;}
}
void Foo<T>(T param1) where T: IA, IB {}
所以两个接口(interface),Foo
方法的第一个参数(param1
)应该实现这两个接口(interface)。
但这真的有用吗?据我所知,在 C# 中无法将一个对象转换为多个接口(interface)?当然一个类可以实现两个接口(interface)。
最佳答案
有时,您的通用逻辑需要同时使用多种类型的功能。例如,我曾经不得不在 ASP.NET 的 Button
、LinkButton
和 ImageButton
控件上执行相同的逻辑。它们各自分别派生自WebControl
并实现了IButtonControl
接口(interface);没有将它们联合起来的基类。
我需要将处理程序连接到由 IButtonControl
公开的 Click
事件,并通过 Attributes
集合设置客户端点击处理程序,它由 WebControl
公开。要启用同时执行这两种操作的方法,我唯一的选择是多类型约束:
private T CreateButton<T>() where T : WebControl, IButtonControl, new()
{
var button = new T();
button.Click += ...;
button.Attributes["onClick"] = ...;
return button;
}
关于c# - 具有多个接口(interface)限制的方法参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3663739/