c# - 具有多个接口(interface)限制的方法参数

标签 c# generics parameters interface

在 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 的 ButtonLinkBut​​tonImageButton 控件上执行相同的逻辑。它们各自分别派生自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/

相关文章:

c# - 字符.IsNumber()

ios - 在 Swift 中使用泛型无法将“对象”转换为 'T'

c++ - 类类型作为参数和作为属性

c# - 非通用接口(interface)是通用接口(interface)的同义词

swift - 如何快速覆盖泛型类中的泛型方法?

Python - 返回构造函数参数名称而不实例化

c# - 如何确保递归调用期间参数不被更改?

c# - 如何填充 ToolStripComboBox?

c# - 显示当前时间 WPF

c# - 加载一定数量的文件而不是扫描并加载目录中的所有文件