简体   繁体   English

没有参数的c#谓词

[英]c# Predicate with no parameters

I'm trying to pass a Predicate to a function but it has no input. 我正在尝试将谓词传递给函数,但是它没有输入。 I'm actually trying to delay the computation until the call is made. 我实际上正在尝试将计算延迟到发出呼叫为止。

Is there a way to use c# Predicate type for that? 有没有办法使用c#谓词类型呢? If not why. 如果不是为什么。

I know a way to do this with Func 我知道使用Func可以做到这一点

Func<bool> predicate = () => someConditionBool;

But I want to do this: 但我想这样做:

Predicate<> predicate = () => someConditionBool;

If it's just a readability problem, then you can create your own delegate which returns boolean and don't have any parameters: 如果这只是可读性问题,那么您可以创建自己的委托,该委托返回boolean并且没有任何参数:

public delegate bool Predicate();

And use it this way 并以这种方式使用

Predicate predicate = () => someConditionBool;

NOTE: You should keep in mind that everyone is familiar with default Action and Func delegates which are used in .NET, but Predicate is your custom delegate and it will be less clear at first time for average programmer. 注意:请记住,每个人都熟悉.NET中使用的默认ActionFunc委托,但是Predicate是您的自定义委托,对于普通程序员来说,第一次使用它就不太清楚了。

Is there a way to use c# Predicate type for that? 有没有办法使用c#谓词类型呢? If not why? 如果不是为什么?

Looking at the signature of Predicate<T> is shows that it requires an argument or parameter: 查看Predicate<T>的签名表明它需要一个参数或参数:

 public delegate bool Predicate<in T>(T obj) 

So the quick answer here would be no. 因此,这里的快速答案是“否”。 Because you have no parameters in your anonymous function. 因为您的匿名函数中没有参数。

But if you play a little around you can give the predicate some irrelevant object which it will not use anyway, like an alibi parameter: 但是,如果您四处游玩,则可以为谓词提供一些无关的对象,该对象无论如何都不会使用,例如alibi参数:

Func<bool> predicate = () => 1 == 1;
Predicate<object> predicate2 = (x) => 1 == 1;

and the call would look like this: 呼叫看起来像这样:

Console.WriteLine(predicate());
Console.WriteLine(predicate2(null));

And this compiles and returns the correct result 然后编译并返回正确的结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM