如何为 C# 泛型集合获取一致的 .Count / .Length 属性?

发布于 2024-10-31 19:49:44 字数 393 浏览 0 评论 0原文

List 具有 .Count 属性,而 T<> 数组则为 .Length。我认为这是因为数组是固定长度的,而其他数组不是,但语法上的差异仍然令人沮丧。

如果您从数组重构为列表,它会给出“不包含 .Length 的定义”错误,并且在 .Count时更改它似乎是浪费时间。长度本质上是相同的。

有没有好的办法来处理这个问题呢?是否可以扩展 List 以添加 .Length 属性(例如,.Count 的别名),反之亦然通用数组?出于某种原因,这会是一个坏主意吗?

List<T> has the .Count property, where as T<> arrays .Length instead. I presume this is because arrays are fixed-length whereas the others aren't, but the difference in syntax can still be frustrating.

If you refactor from an array to list, it therefore gives "does not contain a definition for .Length" errors, and it seems a waste of time having to change it when .Count and .Length are essentially the same.

Is it there a good way to deal with this ? Is it possible to extend List<T> to add an .Length property that's an alias for .Count for instance, and vice-versa for the generic array ? And would this be a bad idea for any reason ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

回眸一笑 2024-11-07 19:49:44

您可以使用 Count LINQ。

经过优化,可以使用 Count 属性由 ICollection界面提供尽可能(或非通用 ICollection .NET 4 中也有接口)。因此数组、List等都将被优化。

var yourList = new List<string> { "the", "quick", "brown", "fox" };
int count1 = yourList.Count();  // uses the ICollection<T>.Count property

var yourArray = new[] { 1, 2, 4, 8, 16, 32, 64, 128 };
int count2 = yourArray.Count();  // uses the ICollection<T>.Count property

var yourEnumerable = yourArray.Where(x => x > 42);
int count3 = yourEnumerable.Count();  // no optimisation, iterates the sequence

或者,如果您想要某种一致的计数属性,而又不想冒在非优化情况下迭代整个序列的风险,那么您可以创建自己的扩展方法。 (我个人不会走这条路。)

int count4 = yourList.GetCount();  // uses the ICollection<T>.Count property
int count5 = yourArray.GetCount();  // uses the ICollection<T>.Count property
int count6 = yourEnumerable.GetCount();  // compile-time error

// ...

public static class CollectionExtensions
{
    public static int GetCount<T>(this ICollection<T> source)
    {
        if (source == null) throw new ArgumentNullException("source");
        return source.Count;
    }

    public static int GetCount(this ICollection source)
    {
        if (source == null) throw new ArgumentNullException("source");
        return source.Count;
    }
}

You can use the Count method provided by LINQ.

This is optimised to use the Count property provided by the ICollection<T> interface where possible (or the non-generic ICollection interface too in .NET 4). So arrays, List<T> etc will all be optimised.

var yourList = new List<string> { "the", "quick", "brown", "fox" };
int count1 = yourList.Count();  // uses the ICollection<T>.Count property

var yourArray = new[] { 1, 2, 4, 8, 16, 32, 64, 128 };
int count2 = yourArray.Count();  // uses the ICollection<T>.Count property

var yourEnumerable = yourArray.Where(x => x > 42);
int count3 = yourEnumerable.Count();  // no optimisation, iterates the sequence

Alternatively, if you wanted a consistent count property of some kind without running the risk of iterating an entire sequence in the non-optimised case then you could create your own extension methods. (I personally wouldn't go down this route.)

int count4 = yourList.GetCount();  // uses the ICollection<T>.Count property
int count5 = yourArray.GetCount();  // uses the ICollection<T>.Count property
int count6 = yourEnumerable.GetCount();  // compile-time error

// ...

public static class CollectionExtensions
{
    public static int GetCount<T>(this ICollection<T> source)
    {
        if (source == null) throw new ArgumentNullException("source");
        return source.Count;
    }

    public static int GetCount(this ICollection source)
    {
        if (source == null) throw new ArgumentNullException("source");
        return source.Count;
    }
}
偏闹i 2024-11-07 19:49:44

您可以将数组放入 IList 类型的变量中。 (数组实现此接口)

然后,您可以像使用任何其他 IList 一样使用该数组(尽管 AddRemove 将抛出异常,因为数组是固定长度的)

You could put your array in a variable of type IList<T>. (arrays implement this interface)

You can then use the array exactly the way you use any other IList<T> (although Add and Remove will throw exceptions, since arrays are fixed-length)

香橙ぽ 2024-11-07 19:49:44

您可以对列表和数组使用 .Count() 方法。

.Count() 方法在可用时运行,然后返回到传统的 .Length

You can use the .Count() method for both List and Arrays.

The .Count() method runs if it is available, then it falls back to the traditional .Length.

哑剧 2024-11-07 19:49:44

您可以简单地扩展通用列表并添加计数方法,但是如果这样做的原因仅仅是因为您的重构并且不想更新为计数,我不建议这样做。如果您没有真正向类添加任何内容,则无需扩展该类。为什么不直接更新代码以使用计数而不是长度呢?

You could simply extend the generic List and add a count method, however if the reason for this is simply because your re-factoring and don't want to update to Count, I don't advise doing so. No need to extend a class if you're not really adding anything to it. Why not just update your code to use Count instead of Length?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文