Default implementation of a method for C# interfaces?

后端 未结 6 2017
梦如初夏
梦如初夏 2020-12-24 05:35

Is it possible to define an interface in C# which has a default implementation? (so that we can define a class implementing that interface without implementing that particul

6条回答
  •  佛祖请我去吃肉
    2020-12-24 06:01

    As a newbe C# programmer I was reading through this topic and wondered if the following code example could be of any help (I don't even know if this is the proper way to do it). For me it allows me to code default behavior behind an interface. Note that I used the generic type specifiction to define an (abstract) class.

    namespace InterfaceExample
    {
        public interface IDef
        {
            void FDef();
        }
    
        public interface IImp
        {
            void FImp();
        }
    
        public class AbstractImplementation where T : IImp
        {
            // This class implements default behavior for interface IDef
            public void FAbs(IImp implementation)
            {
                implementation.FImp();
            }
        }
    
        public class MyImplementation : AbstractImplementation, IImp, IDef
        {
            public void FDef()
            {
                FAbs(this);
            }
            public void FImp()
            {
                // Called by AbstractImplementation
            }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                MyImplementation MyInstance = new MyImplementation();
    
               MyInstance.FDef();
            }
        }
    }
    

提交回复
热议问题