C# Isn';t Func<;T、 布尔>;和谓词<;T>;编译后会发生同样的事情吗?
还没有启动reflector查看差异,但是在比较C# Isn';t Func<;T、 布尔>;和谓词<;T>;编译后会发生同样的事情吗?,c#,.net,predicate,func,C#,.net,Predicate,Func,还没有启动reflector查看差异,但是在比较Func与谓词 我认为没有什么区别,因为它们都接受一个泛型参数并返回bool?它们共享相同的签名,但它们仍然是不同的类型。Robert S.完全正确;例如:- class A { static void Main() { Func<int, bool> func = i => i > 100; Predicate<int> pred = i => i > 100; Tes
Func
与谓词
我认为没有什么区别,因为它们都接受一个泛型参数并返回bool?它们共享相同的签名,但它们仍然是不同的类型。Robert S.完全正确;例如:-
class A {
static void Main() {
Func<int, bool> func = i => i > 100;
Predicate<int> pred = i => i > 100;
Test<int>(pred, 150);
Test<int>(func, 150); // Error
}
static void Test<T>(Predicate<T> pred, T val) {
Console.WriteLine(pred(val) ? "true" : "false");
}
}
A类{
静态void Main(){
Func Func=i=>i>100;
谓词pred=i=>i>100;
试验(pred,150);
测试(func,150);//错误
}
静态无效测试(谓词pred,T val){
控制台写入线(pred(val)-“true”:“false”);
}
}
更灵活的Func
系列只出现在.NET 3.5中,因此它将在功能上复制先前出于必要而必须包含的类型
(加上名称
谓词
将预期用途传达给源代码的读者)即使没有泛型,您也可以拥有签名和返回类型相同的不同委托类型。例如:
namespace N
{
// Represents a method that takes in a string and checks to see
// if this string has some predicate (i.e. meets some criteria)
// or not.
internal delegate bool StringPredicate(string stringToTest);
// Represents a method that takes in a string representing a
// yes/no or true/false value and returns the boolean value which
// corresponds to this string
internal delegate bool BooleanParser(string stringToConvert);
}
在上面的示例中,两个非泛型类型具有相同的签名和返回类型。(实际上也与谓词
和函数
相同)。但正如我试图指出的,两者的“意义”是不同的
这有点像如果我创建两个类,
class Car{string Color;decimal Price;}
和class Person{string FullName;decimal BodyMassIndex;}
,那么仅仅因为它们都持有字符串和十进制,并不意味着它们是“相同的”键入。@Sean-区别在于沟通意图。当我使用谓词时,我的意思是将代码块用作“测试”,并根据测试结果采取操作。当我使用Func
时,我只需要指定一个函数,该函数接受一个参数并返回一个bool。可能重复的