Let's take a look at scottgu's in extension:
Call Example 1:
Call Example 2:
Original article address: New "orcas" Language Feature: extension methods
Many extension methods use "in" as an example, but few people think about it further. I personally feel that this in extension is not thorough enough. refer to the following code: Public static void example1 ()
{
Bool b1 = 1.in( new int [] {1, 2, 3, 4, 5 });
Bool b2 = "Tom". In (New String [] {"Bob", "kitty", "Tom "});
}
// Scottgu in extension
Public static bool in (this object o, ienumerable C)
{
Foreach (object I in C)
{
If (I. Equals (O) return true;
}
Return false;
}
Every time you use in, you need to declare an array (or set), which is a little troublesome. It should be simpler to call it like below: Public static void example2 ()
{
Bool b1 = 1.in( 1, 2, 3, 4, 5 );
Bool b2 = 1.in( 1, 2, 3, 4, 5, 5, 7, 8 );
Bool B3 = "Tom". In ("Bob", "kitty", "Tom ");
Bool B4 = "Tom". In ("Bob", "kitty", "Tom", "Jim ");
}
How do you feel? Is it a bit similar to SQL in?
How to expand it is very simple. Here we use Params, the "method parameter keyword" (the name in msdn). Let's check the code!
Through Params, we do not need to explicitly declare the array, saving a lot of "pen and ink ". // Scottgu in extension Improvement
Public static bool in (this object o, Params object [] C)
{
Foreach (object I in C)
If (I. Equals (O) return true;
Return false;
}
The above has always been an extension of the object, but there is a big risk that your Code may not be noted as below Public static void example3 ()
{
String name = "application1 ";
String name1 = "Bob ";
String name2 = "kitty ";
String name3 = "Tom ";
String S = "Tom ";
Bool b1 = S. In (name1, name2, name3 );
Bool b2 = S. In (name1, name2, name, 3); // Add a comma
}
Compile and run as usual. If an error occurs, it is difficult to find the cause. Fortunately, we have a Generic C # And the last improvement is: // Scottgu in extension Improvement
Public static bool in <t> (this t, Params T [] C)
{
Return C. Any (I => I. Equals (t ));
}
Compile again. The error is as follows:
The problem is solved.
Technical Summary: We use Params and generics to improve the in extension of scottgu. Calling code is more concise, while also reducing incorrect input in programming.
Thought Summary: many articles on the Internet are transferred in and out of their own ideas. There will be many new discoveries as long as you think deeply.
The C # extension method is a special topic and contains many applications. Please stay tuned! Thank you!