2010-04-24 29 views
5

我希望能够写的东西作为如何界定谓词作为函数参数

void Start(some condition that might evaluate to either true or false) { 
    //function will only really start if the predicate evaluates to true 
} 

我猜它一定是形式的东西:

void Start(Predicate predicate) { 
} 

我怎样才能检查里面我的开始函数,只要谓词评估为真或假?我使用的谓词是否正确?

谢谢

回答

10

下面是一个在函数中使用谓词的简单示例。

static void CheckRandomValueAgainstCriteria(Predicate<int> predicate, int maxValue) 
{ 
    Random random = new Random(); 
    int value = random.Next(0, maxValue); 

    Console.WriteLine(value); 

    if (predicate(value)) 
    { 
     Console.WriteLine("The random value met your criteria."); 
    } 
    else 
    { 
     Console.WriteLine("The random value did not meet your criteria."); 
    } 
} 

...

CheckRandomValueAgainstCriteria(i => i < 20, 40); 
2

你可以做这样的事情:

void Start(Predicate<int> predicate, int value) 
    { 
     if (predicate(value)) 
     { 
      //do Something 
     }   
    } 

在那里你调用该方法是这样的:

Start(x => x == 5, 5); 

我不知道这将是多么有用。 Predicates是东西非常方便的像过滤列表:

List<int> l = new List<int>() { 1, 5, 10, 20 }; 
var l2 = l.FindAll(x => x > 5); 
1

从设计的角度来看,谓词的目的被传递给函数通常是过滤掉一些IEnumerable的,正在对每个元素进行测试谓词,以确定是否item是过滤后的集合的成员。

你最好在你的例子中简单地用一个布尔返回类型的函数。

相关问题