不,您不能添加构造函数(即使使用扩展方法)。
假设您有一些从 aFunc<T,T,int>
到 an 的神奇方法IEqualityComparer<T>
(如果您可以引用它,我很想阅读该博客文章)-那么您可以做的最接近的可能是:
public static class HashSet {
public static HashSet<T> Create<T>(Func<T, T, int> func) {
IEqualityComparer<T> comparer = YourMagicFunction(func);
return new HashSet<T>(comparer);
}
}
然而; 我怀疑你可以用 lambda 做什么来表示平等......你有两个概念要表达:散列和真正的平等。你的 lambda 会是什么样子?如果您试图推迟到子属性,那么也许 aFunc<T,TValue>
选择属性,并在EqualityComparer<TValue>.Default
内部使用......类似:
class Person {
public string Name { get; set; }
static void Main() {
HashSet<Person> people = HashSetHelper<Person>.Create(p => p.Name);
people.Add(new Person { Name = "Fred" });
people.Add(new Person { Name = "Jo" });
people.Add(new Person { Name = "Fred" });
Console.WriteLine(people.Count);
}
}
public static class HashSetHelper<T> {
class Wrapper<TValue> : IEqualityComparer<T> {
private readonly Func<T, TValue> func;
private readonly IEqualityComparer<TValue> comparer;
public Wrapper(Func<T, TValue> func,
IEqualityComparer<TValue> comparer) {
this.func = func;
this.comparer = comparer ?? EqualityComparer<TValue>.Default;
}
public bool Equals(T x, T y) {
return comparer.Equals(func(x), func(y));
}
public int GetHashCode(T obj) {
return comparer.GetHashCode(func(obj));
}
}
public static HashSet<T> Create<TValue>(Func<T, TValue> func) {
return new HashSet<T>(new Wrapper<TValue>(func, null));
}
public static HashSet<T> Create<TValue>(Func<T, TValue> func,
IEqualityComparer<TValue> comparer)
{
return new HashSet<T>(new Wrapper<TValue>(func, comparer));
}
}