In c#2.0, the collaboration of anonymous methods, IEnumerable interfaces, and anonymous methods makes many programming tasks very simple, and the written program is very graceful.
For example, we could write the following code:
List<Book> thelib = Library.getbooks();
List<Book> found = thelib.FindAll(delegate(Book curbook)
{
if (curbook.isbn.StartsWith("..."))
return true;
return false;
});
foreach (Book b in found)
Console.WriteLine(b.isbn);
This program is very simple to show us the information we need to find, and the code is very straightforward. The built-in data structure gives us powerful algorithm support, but is it possible to define a similar algorithm for a custom class?
For example, if I have a custom library class that does not use list to store data, but instead uses some sort of custom data structure, can I also allow users to use similar syntax, ignoring the use of anonymous delegates to store details to implement a particular algorithm?
The answer is certainly yes, and in C # It is very simple to implement such a function.
First, let's look at the prototype of the anonymous delegate used in FindAll.
Public delegate BOOL predicate (T obj);
Obviously, the code above is equivalent to registering a callback for a search, and defining some sort of traversal mechanism within the list, thus achieving a beautiful algorithm structure closure.
Seeing these, we can define our own algorithm structure, first of all, I define a class like the following
public class MyVec<T>
{
public static MyVec<T> operator +(MyVec<T> 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();
return ret;
}
public MyVec<T<>findAll(Predicate<T> act)
{
MyVec<T:>t2 = new MyVec<T>();
foreach(T i in _list)
{
if (act(i))
t2._list.Add(i);
}
return t2;
}
// this is the inner object
private List<T> _list = new List<T>();
}
This class contains a list structure, mainly to verify that our idea is feasible, in fact, any structure that can support a foreach traversal can be used as a built-in data storage object, and we'll give a more complex implementation in the example that follows.