学习有效地使用接口 [英] Learning to use Interfaces effectively

查看:121
本文介绍了学习有效地使用接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在开发C#软件一段时间,但我没有足够有效使用一个主要领域是接口。事实上,我经常感到他们可以用不同的方式和何时使用它们混淆。例如,我知道方法可以返回接口,可以把它们作为参数,可以从中获得等这个概念对我来说是一个明确的弱点

我想知道是否有人知道的源/教程,清楚而全面地说明了在深度和它们可用于各种方式的接口?


解决方案

说明


  

在C#接口提供一种方法来实现运行时多态性。使用接口,我们可以通过相同的接口调用参考来自不同类的功能,而使用虚函数我们可以通过相同的参考援引来自同一个继承层次不同类别的功能。


例如:

 公共类FileLog:ILog的
{
    公共无效日志(字符串文本)
    {
        //写文本文件
    }
}公共类DatabaseLog:ILog的
{
    公共无效日志(字符串文本)
    {
        //写文本到数据库
    }
}公共接口的ILog
{
    无效日志(字符串文本);
}公共类SomeOtherClass
{
    私人的ILog _logger;    公共SomeOtherClass(ILog的记录仪)
    {
        //我不知道,如果记录器是FileLog或DatabaseLog
        //但我并不需要知道无论是只要其执行的ILog
        this._logger =记录仪;
        logger.Log(的Hello World!);
    }
}

您要求的教程。

教程

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 they can be used and when to use them. For example, I know methods can return interfaces, can take them as parameters, can be derived from them etc. This concept is a definite weakness for me

I was wondering if anyone knew of a source / tutorial that clearly and thoroughly explains interfaces in depth and the various ways they can be used?

解决方案

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

这篇关于学习有效地使用接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆