1

代表们,是的,我正在尝试理解这个概念的使用,它有助于在 C# 中解决哪些问题。到目前为止,我真的很喜欢它提供代码的解耦工具。然后我遇到了谓词代表。根据this MSDN library article,它表明它们是接受任何数据类型参数并返回bool类型值的委托......。

它还说,这个特定的委托接受泛型,<T>可以说是任何类型......

那么说 Predicate Delegate 只是一个 Boolean Delegate 是否正确?这意味着任何具有布尔返回类型的委托?或者是否有更多用于指定不同名称:谓词代表..?

例如

delegate bool BooleanDelegate(anytype parameter);
BooleanDelegate bd = new BooleanDelegate(yesno);     
//assuming parameter type is int
MessageBox.Show(bd.Invoke(2).ToString());

public bool yesno(anytype parameter)
{      
   If (parameter == 2)
    {
       return true;
    }
   Else
    {
       return false;
    }     
}
4

2 回答 2

3

一般来说,谓词是一个布尔值函数。所以是的,任何返回布尔值的函数都是谓词。

于 2013-02-23T20:45:56.850 回答
2

是的,aPredicate<T>代表一个方法,它接受一个类型的参数T,并返回bool。例如, aPredicate<string>表示一个接受 astring并返回 a的方法bool

例如:

Predicate<string> p = String.IsNullOrEmpty;  // this static method has the correct signature and return type

你可以说

bool answer = p("your words");

泛型意味着T在不同的情况下可以有不同的含义。因此,您不必制作一大堆委托类型,例如StringPredicate, DateTimePredicate,BicyclePredicate等,但您可以使用Predicate<DateTime>, Predicate<Bicycle>, ...

APredicate<T>具有与 a 相同的签名和返回类型Func<T, bool>(在 .NET 版本 3.5 中引入)。两者都是逆变的T

你:

那么说 Predicate Delegate 只是一个 Boolean Delegate 是否正确?

它的签名必须是正确的。必须只有一个参数(不是零,也不是两个或更多)。参数不能是refor out。参数必须具有正确的类型T(但 的含义T可能不同)。例如,接受 a 的方法Bicycle可能是 a Predicate<Bicycle>,但不是 a Predicate<DateTime>

于 2013-02-23T20:57:46.617 回答