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();
}
}
标签:
windows-runtime