With the extension method technology provided by C # 3.0, you can add new methods to the compiled assembly type to cope with the new extension. In addition to the advantages of scalability, if you can reasonably combine generics with type inference, extension methods can effectively reduce the duplication of code and improve the reusability of programs. For example, this method implements the following:
public class Customerdal
{public
ienumerable<customer> findcustomers (string rolename)
{
Return from the customer in context
. Customer
where customer. Rolename.equals (rolename)
Select customer;
}
When the result returned by the method is null, the NullReferenceException exception is thrown by using the following method:
Customer customer = new Customerdal (). Findcustomers (role.admin). A ();
We need to validate the return result, and if we return to NULL, we can throw a custom exception, or create an empty object, for example:
Public ienumerable<customer> findcustomers (string rolename)
{
ienumerable<customer> customers = From the customer in context
. Customer
where customer. Rolename.equals (rolename)
Select customer;
if (customers = = null)
{
throw new MyException ("Cann ' t find the customers.");
}
return customers;
}
If there are many methods in the system that require validation of the return results, such validation logic will be flooded into the body of the method, which is not conducive to reuse, and can be a great hindrance to future modifications. Of course, we can introduce the null object pattern to replace the judgment logic for null values, but this way we still need to define different null object types for multiple types.