【问题标题】:Can predicate delegate simply be called as a boolean delegate?谓词委托可以简单地称为布尔委托吗?
【发布时间】:2013-02-23 20:37:24
【问题描述】:

各位代表,是的,我想了解这个概念的用途,它有助于在 C# 中解决哪些问题。到目前为止,我真的很喜欢它提供代码的解耦工具。然后我遇到了谓词代表。根据this MSDN library article it shows they are, delegates that takes any data type paramter and returns a bool type value...

它还说,这个特定的委托接受泛型,<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;
    }     
}

【问题讨论】:

    标签: c# delegates boolean predicate


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      例如:

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

      你可以这么说

      bool answer = p("your words");
      

      泛型意味着T在不同的情况下可以有不同的含义。因此,您不必创建一大堆委托类型,例如 StringPredicateDateTimePredicateBicyclePredicate 等,但您可以使用 Predicate&lt;DateTime&gt;Predicate&lt;Bicycle&gt;、...

      Predicate&lt;T&gt;Func&lt;T, bool&gt; 具有相同的签名和返回类型(在 .NET 版本 3.5 中引入)。两者在T 中都是逆变的。

      你:

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

      它的签名必须是正确的。必须只有一个参数(不是零,也不是两个或更多)。参数不得为refout。参数必须具有正确的类型T(但T 的含义可能不同)。例如,接受Bicycle 的方法可能是Predicate&lt;Bicycle&gt;,但不是Predicate&lt;DateTime&gt;

      【讨论】:

      • 谢谢,对不起,我花了一些时间来体验,并且在同一行有更多问题 :) 你说 参数不能是 ref 或 out。 b>,所以它必须是param?
      • 当我们查看Predicate&lt;&gt;signature 时,我们看到T obj 参数not 带有params 修饰符。它不能,因为我们不知道T 是否是一个数组SomeType[]。当委托类型签名没有params 时,如果方法有params,则方法必须以其未扩展的形式应用。例如。如果方法是static bool Meth(params string[] args) { ... },那么你可以说Predicate&lt;string[]&gt; p1 = Meth;,但是你不能扩展,所以它不会和Predicate&lt;string&gt; p2 = Meth;一起工作。
      猜你喜欢
      • 2011-01-12
      • 2010-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-25
      • 1970-01-01
      相关资源
      最近更新 更多