gpt4 book ai didi

c# - 列表和集合的通用约束

转载 作者:行者123 更新时间:2023-12-02 03:04:28 24 4
gpt4 key购买 nike

我有一个通用方法,看起来像这样:

public int GetCount<T>(T collection) where T: ICollection
{
return collection.Count;
}

现在我希望能够调用此方法,其中集合参数可以是 List<T>HashSet<T> 。当前的代码不满足这一点,因为我想要传递的参数不继承 ICollection界面。现在有什么方法可以通过简单的约束来实现这一点吗?

最佳答案

为什么不:

public int GetCount<T>(ICollection<T> collection)
{
return collection.Count;
}

关于c# - 列表和集合的通用约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59321632/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com