Is there any kind of “ReferenceComparer” in .NET?

寵の児 提交于 2019-12-03 22:39:28

As far as I know, the BCL doesn't expose any public types that implement IEqualityComparer<T> with reference-equality as of .NET 4.0 .

However, there do appear to be a bunch of internal types that do this, such as:

  • System.Dynamic.Utils.ReferenceEqualityComparer<T> (in System.Core)
  • System.Xaml.Schema.ReferenceEqualityComparer<T> (in System.Xaml).

I took a look at the implementations of these two types with reflector, and you'll be happy to know that both of them appear to be implemented in a way that is virtually identical to yours, except that they don't use lazy-initialization for the static instance (they create it in the static constructor for the type).

The only possible 'issue' I can think of with your implementation is that the lazy-initialization is not thread-safe, but since instances are 'cheap' and aren't holding onto any state, that shouldn't create any bugs or major performance problems. If you want to enforce the singleton-pattern though, you'll have to do it properly.

I end up using this solution also as I could not find any workaround.

To fix the non thread safe implementation, you could easily use a static initiailizer.

public static ReferenceComparer<T> Instance => new ReferenceComparer<T>();

(sorry for the answer instead of a comment to up-voted thread, I have a new account with no comment rights, yet).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!