c# - 强制我的容器类只接受实现 IComparable 的对象的最佳方法是什么?

标签 c#

我正在学习 C#。进行以下练习以使用功能。

我有这个类作为我的容器:

class myContainer<T> : List<T>

当我将此结构添加到容器时,它工作正常,因为它具有 IComparable 的实现

interface bla<T> : IComparable<T> {}
struct IString : bla<IString>

当我添加一个没有通过接口(interface)或直接实现 IComparable 的类时,如果我执行类似 Sort() 的操作,我会在运行时收到错误

强制我的容器类只接受实现 IComparable 的对象的最佳方法是什么?

谢谢

最佳答案

class myContainer<T> : List<T>
    where T : IComparable<T>
{
    ...
}

如果可能,您可能还想考虑为您的类支持 IComparable(非泛型版本)。

This MSDN article on generic constraints有关于 where 表达式的更多信息。

关于c# - 强制我的容器类只接受实现 IComparable 的对象的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2402666/

相关文章:

c# - 相当于 do() while{} 在并行

C# Linq 多或

c# - Azure函数HTTP触发器不取消请求

c# - 避免时钟程序中的溢出错误

c# - 变量不持有值

c# - AddDbContext 在 ASP.NET Core Razor 页面的配置服务中不起作用

c# - 如何优雅地处理ASP.NET MVC 4中的数据库连接?

c# - 如何在不重新安装的情况下更新winform应用程序

c# - c#中使用AFORGE录制视频

c# - 具有更改哈希码的 WPF 列表框和项目