Learning to use Interfaces effectively

后端 未结 2 1858
小蘑菇
小蘑菇 2020-12-07 11:13

I\'ve been developing software in C# for a while, but one major area that I don\'t use effectively enough is interfaces. In fact, I\'m often confused on the various ways the

2条回答
  •  春和景丽
    2020-12-07 11:58

    Description

    Interfaces in C # provide a way to achieve runtime polymorphism. Using interfaces we can invoke functions from different classes through the same Interface reference, whereas using virtual functions we can invoke functions from different classes in the same inheritance hierarchy through the same reference.

    For example:

    public class FileLog : ILog
    {
        public void Log(string text)
        {
            // write text to a file
        }
    }
    
    public class DatabaseLog : ILog
    {
        public void Log(string text)
        {
            // write text to the database
        }
    }
    
    public interface ILog
    {
        void Log(string text);
    }
    
    public class SomeOtherClass
    {
        private ILog _logger;
    
        public SomeOtherClass(ILog logger)
        {
            // I don't know if logger is the FileLog or DatabaseLog
            // but I don't need to know either as long as its implementing ILog
            this._logger = logger;
            logger.Log("Hello World!");
        }    
    }
    

    You asked for tutorials.

    Tutorials

    • MSDN - Interfaces (C# Programming Guide)
    • CodeGuru - Interfaces in C#
    • C# Interface Based Development
    • Codeproject - Interfaces in C# (For Beginners)

提交回复
热议问题