Bre*_*ier 6 .net c# collections lambda dictionary
例如,类似于:
Dictionary<string, Func<T1, T2, bool>> comparisons;
comparisons.add("<", (x, y) => x < y);
comparisons.add("==", (x, y) => x == y);
comparisons.add(">", (x, y) => x > y);
Run Code Online (Sandbox Code Playgroud)
在这一点上,我对C#lambdas和多类型通用容器知之甚少,无法正确地将它们放在一起.这甚至可能吗?
是的,拥有这样的东西是完全有效的:
Dictionary<string, Func<int, int, bool>> comparisons = new Dictionary<string, Func<int, int, bool>>();
comparisons.Add("<", (x, y) => x < y);
comparisons.Add("==", (x, y) => x == y);
comparisons.Add(">", (x, y) => x > y);
Run Code Online (Sandbox Code Playgroud)
在您的示例中,您需要使用Func<int, int, bool>,因为您接受两个参数并返回一个布尔值.
你也可以把它放在一个通用的实现中,但是你需要某种方法来约束它,这样任何东西都必须实现<,==和>运算符.
泛型类型必须在编译时已知,因此无法进行动态委托。如果指定数据类型,则可以创建委托字典:
Dictionary<string, Func<int, int, bool>> comparisons;
comparisons.add("<", (x, y) => x < y);
comparisons.add("==", (x, y) => x == y);
comparisons.add(">", (x, y) => x > y);
Run Code Online (Sandbox Code Playgroud)
您可以使用该IComparable接口来允许不同的类型,但是您只能使用它的CompareTo方法来实现运算符:
Dictionary<string, Func<IComparable, IComparable, bool>> comparisons;
comparisons.add("<", (x, y) => x.CompareTo(y) < 0);
comparisons.add("==", (x, y) => x.CompareTo(y) == 0);
comparisons.add(">", (x, y) => x.CompareTo(y) > 0);
Run Code Online (Sandbox Code Playgroud)
当然,这对所使用的数据的限制较少,例如,您可以将 astring和DateTime值提供给运算符委托,并且它可以很好地编译。直到你运行它才失败。
| 归档时间: |
|
| 查看次数: |
360 次 |
| 最近记录: |