我为什么不能打电话的OrderBy在扩展列表类? [英] Why can't I call OrderBy in a class that extends List?

查看:187
本文介绍了我为什么不能打电话的OrderBy在扩展列表类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,甲板,它包含一个名为方法随机

I have a class, Deck, that contains a method called Shuffle.

我正在重构甲板延长名单,其中,卡> ,而不是列表与LT;卡>卡作为属性。然而,尽管 Cards.OrderBy(A => Guid.NewGuid())工作排序依据(A => Guid.NewGuid())

I'm working on refactoring Deck to extend List<Card>, rather than having List<Card> Cards as a property. However, while Cards.OrderBy (a => Guid.NewGuid ()) worked, OrderBy (a => Guid.NewGuid ()) does not:

错误CS0103:名称排序依据并不在当前的背景下(CS0103)存在

为什么这个不工作?

推荐答案

添加排序依据的前面在

this.OrderBy(a => Guid.NewGuid()); // a random ordering

排序依据的IEnumerable℃的扩展方法; T&GT; ,而不是在<$ C $的公共方法C>列表&LT; T&GT; 。如果你键入排序依据有没有上下文的编译器会寻找一个实例或命名为排序依据静态方法。只有当你preFIX 排序依据的IEnumerable&LT的实例; T&GT; 将编译器找到排序依据。由于甲板:列表&LT;卡&GT; 名单,其中,卡&GT; :IEnumerable的&LT;卡&GT; ,使用关键字(参考当前实例)会给编译器,它需要找到方法的上下文 Enumerable.OrderBy

OrderBy is an extension method on IEnumerable<T> and is not a public method on List<T>. If you type OrderBy with no context the compiler will look for an instance or static method named OrderBy. It is only if you prefix OrderBy with an instance of IEnumerable<T> will the compiler find OrderBy. As Deck : List<Card> and List<Card> : IEnumerable<Card>, using the keyword this (a reference to the current instance) will give the compiler the context it needs to locate the method Enumerable.OrderBy.

它被认为是不好的做法,从<$ C $继承C>列表&LT; T&GT; 在一个公共的API 。首先,名单,其中,T&GT; 不是为继承和可能应该是密封;现在太晚了。一般情况下,你应该使用框架类时,有利于组成了继承。

It is considered bad practice to inherit from List<T> in a public API. First, List<T> was not designed for inheritance and probably should have been sealed; too late for that now. In general, you should favor composition over inheritance when using framework classes.

这篇关于我为什么不能打电话的OrderBy在扩展列表类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆