Predicate Delegates in C#

后端 未结 10 1394
一个人的身影
一个人的身影 2020-11-27 09:13

Can you explain to me:

  • What is a Predicate Delegate?
  • Where should we use predicates?
  • Any best practices when using predicates?

10条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 09:47

    Predicate falls under the category of generic delegates in C#. This is called with one argument and always return the boolean type. Basically, the predicate is used to test the condition - true/false. Many classes support predicate as an argument. For example, list.findall expects the parameter predicate. Here is an example of predicate.

    Imagine a function pointer with the signature:

     bool delegate myDelegate(T match);
    

    Here is the example:

    Node.cs:

    namespace PredicateExample
    {
        class Node
        {
            public string Ip_Address { get; set; }
            public string Node_Name { get; set; }
            public uint Node_Area { get; set; }
        }
    }
    

    Main class:

    using System;
    using System.Threading;
    using System.Collections.Generic;
    
    namespace PredicateExample
    {
        class Program
        {
            static void Main(string[] args)
            {
                Predicate backboneArea = Node =>  Node.Node_Area == 0 ;
                List Nodes = new List();
                Nodes.Add(new Node { Ip_Address = "1.1.1.1", Node_Area = 0, Node_Name = "Node1" });
                Nodes.Add(new Node { Ip_Address = "2.2.2.2", Node_Area = 1, Node_Name = "Node2" });
                Nodes.Add(new Node { Ip_Address = "3.3.3.3", Node_Area = 2, Node_Name = "Node3" });
                Nodes.Add(new Node { Ip_Address = "4.4.4.4", Node_Area = 0, Node_Name = "Node4" });
                Nodes.Add(new Node { Ip_Address = "5.5.5.5", Node_Area = 1, Node_Name = "Node5" });
                Nodes.Add(new Node { Ip_Address = "6.6.6.6", Node_Area = 0, Node_Name = "Node6" });
                Nodes.Add(new Node { Ip_Address = "7.7.7.7", Node_Area = 2, Node_Name = "Node7" });
    
                foreach( var item in Nodes.FindAll(backboneArea))
                {
                    Console.WriteLine("Node Name " + item.Node_Name + " Node IP Address " + item.Ip_Address);
                }
    
                Console.ReadLine();
            }
        }
    }
    

提交回复
热议问题