在c# 4.0中可以创建一个多类型lambda函数的多类型集合
本文关键字:多类型 一个 lambda 集合 函数 创建 | 更新日期: 2023-09-27 17:54:46
例如:
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);
在这一点上,我对c# lambda和多类型泛型容器的了解还不够,无法正确地将它们组合在一起。这可能吗?
是的,像这样的东西是完全有效的:
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);
在您的示例中,您需要使用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);
你可以使用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);
这当然减少了对所使用数据的限制,例如,您可以向操作符委托提供string
和DateTime
值,并且它编译得很好。直到你运行它,它才会失败。
Func<int, int, bool> t = null;
var comparisons = new Dictionary<string, Func<int, int, bool>>
{
{"<", (x, y) => x < y},
{"==", (x, y) => x == y},
{">", (x, y) => x > y}
};
t = comparisons["<"];
bool result = t(1,2);
是的,可以这样做,但是只有在所有泛型类型参数都给定具体类型的情况下才能这样做。例如,可以这样做:
Dictionary<string, Func<int, int, bool>> comparisons = new Dictionary<string, Func<int, int, bool>>();
没有办法这样做(在伪c++语法中):
Dictionary<string, Func<?, ?, bool>> comparisons = new Dictionary<string, Func<?, ?, bool>>();
我不明白有T1和T2的意义;如果有不同的类型你通常无法比较,对吧?
如果你想保持它的泛型,你可以这样做(我将比较字典存储在这里的一个字段中):
class MyClass<T> where T:IComparable<T>
{
private Dictionary<string, Func<T, T, bool>> comparisons
= new Dictionary<string, Func<T, T, bool>>
{
{"<", (x, y) => x.CompareTo(y) < 0},
{"==", (x, y) => x.Equals(y)},
{">", (x, y) => x.CompareTo(y) > 0}
};
}