In C # 2.0, cooperation with anonymous methods, IENUMERABLE interfaces, and anonymous methods, making many programming tasks very simple, and the procedures written are very beautiful.
For example, we can write the following code:
List Thelib = library.getbooks (); list Found = thelib.findall (curbook) {if (Curbook.isbn.StartSwith ("...")) Return true;} Forueach (BOOK B IN FOUND) Console.WriteLine (B.isbn);
This program is very simple to show what you need to find, and the code is also very easy to understand. The built-in data structure gives us strong algorithm support, but can it be similar to the similar algorithm for custom class?
For example, if I have a custom library class, I don't use list to store data, but use some custom data structure, I can also allow users to use similar syntax, ignore the use of storage details Anonymous commission To achieve a specific algorithm?
The answer is of course affirmative, and this function is very simple in C #.
First let's take a look at the prototypes used by the anonymous entrusted in FindAll
Public Delegate Bool Predicate (T Obj);
Obviously, the above code is equal to registering a search for callback, and a mechanism for a traversal is defined within the List, thereby implementing a beautiful algorithm structure Closure.
Seeing this, we can define your own algorithm structure. First, I define a class as follows.
Public class myvec {public static myvec Operator (MyVEC a, t b) {a._list.add (b); return a;} public override string toString () {StringBuilder Builder = New Stringbuilder (); foreach (t a in _list) {builder.append (a.tostring ()); builder.Append (",");} string ret = builder.remove (Builder.Length - 1, 1) .tostring ();} Public myvec FindAll (Predicate ACT) {MyVEC T2 = new MyVEC (); Foreach (T i in _list) {if (ACT (i ))) T2._List.Add (i);} Return T2;} // this is the inner object private list _list = new list ();}
This class contains a List structure, mainly to confirm that our ideas are feasible, in fact, any structure that can support foreach traversal can be used as a built-in data storage object, we will be in the following example A more complex implementation is given. Below is the code used to test this experiment class:
Static void main (string [] args) {MyVEC a = new myvec (); A = 12; A = 15; A = 32; MyVEC b = a.findall (Delegate (INT X) {IF (x <20) return true; return false;}; console.writeLine ("vection original"); console.writeline (a.tostring ()); console.writeline ("vection found") Console.writeline (B. Tostring ()); console.readline ();
Compile, execute, program output:
VECTION Original12, 15, 32Vection Found32
And we expect exactly the same. Obviously, the algorithm within the List is the same as we expect.
Predicate is just a delegate adopted in order to imitate the implementation of the system.
By using the IenumBerable interface, it is possible to realize the traversal of any structure, thereby defining a powerful algorithm support for any data structure.