c# - 是否可以强制泛型类从两个接口(interface)之一继承类型?

标签 c# .net generics

我有一个泛型类,但我希望我的类型强制从一个或另一个接口(interface)继承。例如:

public class MyGeneric<T> where T : IInterface1, IInterface2 {}

以上将强制 T 从 IInterface1 和 IInterface2 继承,但我可以强制 T 从 IInterface1 或 IInterface2 (或两者)继承吗?

最佳答案

定义一个基本接口(interface)——它甚至不必有任何成员,并让 Interface1 和 Interface2 都扩展它。然后将 T 的范围设为基本接口(interface)类型。仅当您希望从接口(interface)派生通用接口(interface)而不是框架中的任何现有接口(interface)时,这才有效。

public interface BaseInterface
{
}

public interface Interface1 : BaseInterface
{
    void SomeMethod();
}

public interface Interface2 : BaseInterface
{
    void SomeOtherMethod();
}

public class MyGenericClass<T> where T : BaseInterface
{
    ...
}

var myClass1 = new MyGenericClass<Interface1>();

var myClass2 = new MyGenericClass<Interface2>();

关于c# - 是否可以强制泛型类从两个接口(interface)之一继承类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/525158/

相关文章:

c# - 检查类型是否派生自抽象泛型类

generics - 如何在 Rust 的泛型函​​数中同时使用非拥有迭代器和消耗迭代器?

c# - 从字符串语句中删除最后一个逗号

c# - 像在 C# 中一样在 Javascript 中强制转换为 float

c# - C# 中的日期和时间转换 - DateTime.ParseExact() 未按预期工作

.net - 使用 ApplicationSettings 存储 WinForms RadioButtons 的 Checked 属性

c# - AutoMapper 通用转换

c# - 如何设置项目的调试实例内存限制

c# - 删除数组中的最后一个元素,插入新元素

c# - Windows Forms .NET 中的 DataGridViewRow 线程安全