How to make C# Windows Runtime Component types equatable?

无人久伴 提交于 2019-12-24 00:55:20

问题


I'm writing a Windows Runtime Component in C#. I want to implement the IEquatable interface in some of my types. I don't need to expose the Equals method to the consumers of the component, I just want my unit tests to be able to compare between instances. Implementing IEquatable is not allowed because it's a generic type. What would be the best alternative?


回答1:


Unfortunately there is no mechanism for implementing deep comparison between two winrt types :(.




回答2:


According to https://msdn.microsoft.com/EN-US/library/bsc2ak47(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp

The .Net Framework supplies default implementation for ToString(), Equals(Object) and GetHashCode to WinRT types.

When the default EqualityComparer is used on a type that does not implement IEquatable it defaults to Equals(Object).

So to mimic IEquatable for a WinRT type you just need to override Object.Equals on your type. This requires you also override GetHashCode.

Here is an example class:

using System;

public sealed class BindableInt
{
  public BindableInt(int i = 0)
  {
   Value = i;
  }
  public int Value { get; set; }
  public string String
  {
    get 
    {
      return Value.ToString();
    }
  }
  public override bool Equals(object obj)
  {
    if (!(obj is BindableInt)) return false;
      return Value.Equals(((BindableInt)obj).Value);
  }
  public override int GetHashCode()
  {
    return Value.GetHashCode();
  }
}


来源:https://stackoverflow.com/questions/18129477/how-to-make-c-sharp-windows-runtime-component-types-equatable

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