Delegates vs Interfaces in C#

后端 未结 5 685
遇见更好的自我
遇见更好的自我 2021-01-30 00:37

I would like to pose this question as long as I am trying currently to dig into the use and the purpose of delegates, although it is likely to have been asked in similar formula

5条回答
  •  误落风尘
    2021-01-30 01:26

    The biggest practical difference is that you can provide different delegate instances for the same delegate from the same class, while you cannot do it with interfaces.

    delegate void XYZ(int p);
    
    interface IXyz {
        void doit(int p);
    }
    
    class One {
        // All four methods below can be used to implement the XYZ delegate
        void XYZ1(int p) {...}
        void XYZ2(int p) {...}
        void XYZ3(int p) {...}
        void XYZ4(int p) {...}
    }
    
    class Two : IXyz {
        public void doit(int p) {
            // Only this method could be used to call an implementation through an interface
        }
    }
    

提交回复
热议问题