gpt4 book ai didi

c# - 扩展方法中where子句关键字的含义

转载 作者:行者123 更新时间:2023-12-03 22:56:20 24 4
gpt4 key购买 nike

我一直在关注来自 post 的关于扩展方法的帖子:

public static IEnumerable<T> Distinct<T,TKey>(this IEnumerable<T> list, Func<T,TKey> lookup) where TKey : struct {
return list.Distinct(new StructEqualityComparer<T, TKey>(lookup));
}

class StructEqualityComparer<T,TKey> : IEqualityComparer<T> where TKey : struct {

Func<T, TKey> lookup;

public StructEqualityComparer(Func<T, TKey> lookup) {
this.lookup = lookup;
}

public bool Equals(T x, T y) {
return lookup(x).Equals(lookup(y));
}

public int GetHashCode(T obj) {
return lookup(obj).GetHashCode();
}
}

有人可以解释 where TKey : struct 附加到扩展方法和比较器类的目的。删除这些语句似乎对简单的测试代码没有影响 - 两个评估 TKey 分别是类和结构上的 int 类型:

public struct TestMeStruct
{
public int a;
public int b;
}

public class TestMeClass
{
public int a { get; set; }
public int b { get; set; }

}

public void Test()
{

List<TestMeStruct> lstruct = new List<TestMeStruct>();

lstruct.Add(new TestMeStruct() { a = 1, b = 2 });
lstruct.Add(new TestMeStruct() { a = 3, b = 7 });
lstruct.Add(new TestMeStruct() { a = 3, b = 14 });
lstruct.Add(new TestMeStruct() { a = 32, b = 11 });


List<TestMeClass> lclass = new List<TestMeClass>();
lclass.Add(new TestMeClass() { a = 1, b = 2 });
lclass.Add(new TestMeClass() { a = 3, b = 7 });
lclass.Add(new TestMeClass() { a = 3, b = 14 });
lclass.Add(new TestMeClass() { a = 32, b = 11 });

var one = lstruct.Distinct(mem => mem.a).ToList();
var two = lclass.Distinct(mem => mem.a).ToList();
}

两者都返回相同的列表。非常感谢您清楚地了解正在发生的事情!

最佳答案

来自 msdn

The where clause is used to specify constraints on the types that can be used as arguments for a type parameter defined in a generic declaration. For example, you can declare a generic class, MyGenericClass, such that the type parameter T implements the IComparable interface:

public class MyGenericClass where T:IComparable { }

关于c# - 扩展方法中where子句关键字的含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8657790/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com