How do I extend a class with c# extension methods?

后端 未结 9 1377
情书的邮戳
情书的邮戳 2020-12-04 10:48

Can extension methods be applied to the class?

For example, extend DateTime to include a Tomorrow() method that could be invoked like:

DateTime.Tomor         


        
9条回答
  •  时光取名叫无心
    2020-12-04 11:17

    We have improved our answer with detail explanation.Now it's more easy to understand about extension method

    Extension method: It is a mechanism through which we can extend the behavior of existing class without using the sub classing or modifying or recompiling the original class or struct.

    We can extend our custom classes ,.net framework classes etc.

    Extension method is actually a special kind of static method that is defined in the static class.

    As DateTime class is already taken above and hence we have not taken this class for the explanation.

    Below is the example

    //This is a existing Calculator class which have only one method(Add)

    public class Calculator 
    {
        public double Add(double num1, double num2)
        {
            return num1 + num2;
        }
    
    }
    
    // Below is the extension class which have one extension method.  
    public static class Extension
    {
        // It is extension method and it's first parameter is a calculator class.It's behavior is going to extend. 
        public static double Division(this Calculator cal, double num1,double num2){
           return num1 / num2;
        }   
    }
    
    // We have tested the extension method below.        
    class Program
    {
        static void Main(string[] args)
        {
            Calculator cal = new Calculator();
            double add=cal.Add(10, 10);
            // It is a extension method in Calculator class.
            double add=cal.Division(100, 10)
    
        }
    }
    

提交回复
热议问题