IEqualityComparer 和单例
我想知道是否有可能在例如 Distinct 中使用单例作为比较对象?
假设我有一个元素列表,我需要在该列表上使用不同的函数。通常我会这样做,
var result = list.Distinct(new ListElementComparer);
ListElementComparer 是一个实现 IEqualityComparer 接口的类。 然而,让我们假设我将非常频繁地使用上面提到的代码,例如那样。
List<List<Element>> elementList = new List<List<Elements>>();
List<List<Element>> resultList new List<List<Element>>();
foreach(var element in elementList )
resultList.AddRange(element.Distinct(new ListElementComparer() ) );
因此,您可以看到 ListElementComparer 的对象可能会被创建很多次。在这种情况下,是否有必要在每次迭代中使用 singletone 而不是创建 ListElementComparer ?如果我使用单例,独特的方法会起作用吗?
I was wondering if there is possibility to use singleton as comparerObject in for example Distinct ??
Let's say that I have a list of element and I need to use distinct function on that list. Normally I would do that this way
var result = list.Distinct(new ListElementComparer);
ListElementComparer is a class which implements IEqualityComparer interface.
However let's assume that I will be using code mentioned above quite frequently for example that way .
List<List<Element>> elementList = new List<List<Elements>>();
List<List<Element>> resultList new List<List<Element>>();
foreach(var element in elementList )
resultList.AddRange(element.Distinct(new ListElementComparer() ) );
So as You can object of ListElementComparer might be created quite a lot of times. In this case is there any point of using singletone insted of createing ListElementComparer in each iteration ? Will the distinct method work if I use singleton ??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,绝对,它可以与单例一起正常工作:
然后:
请注意,可以在某种程度上避免整个循环:(
这对于最初声明的类型不太适用,因为您的示例代码也不太适用..但类似的东西会。)
Yes, absolutely, it will work fine with a singleton:
Then:
Note that your whole loop can be avoided somewhat:
(This doesn't quite work with the originally-declared types, because your sample code doesn't quite work either... but something similar would.)