c# - 学习有效地使用接口(interface)

标签 c#

我用 C# 开发软件已有一段时间,但我使用得不够有效的一个主要领域是接口(interface)。事实上,我经常对它们的各种使用方式和何时使用感到困惑。例如,我知道方法可以返回接口(interface),可以将它们作为参数,可以从它们派生等。这个概念对我来说是一个明确的弱点

我想知道是否有人知道一个源代码/教程,它清楚而透彻地深入解释了界面以及它们的各种使用方式?

最佳答案

描述

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.

例如:

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!");
    }    
}

您要求提供教程。

教程

关于c# - 学习有效地使用接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8701345/

相关文章:

c# - EF Core 添加迁移调试

c# - 如何启用 nginx 反向代理以在 .Net 核心中与 gRPC 一起使用?

c# - C# 泛型类型的测试分配

c# - 为什么这种继承不起作用?

c# - 如何使用命令行参数在 C# 中创建应用程序快捷方式(.lnk 文件)

c# - 将此 C# 代码转换为经典 ASP/VBScript?

c# - 如何从 System.Linq.Expressions.Expression 中删除括号?

c# - 如何为Windows应用程序创建.exe文件

c# - 发布 WPF .Net Core 3 应用程序和 Serilog.Sinks.File

c# - 将两种扩展方法合二为一