本文介绍了接口只是将类标记为具有通用功能的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编程新手。我已经看到过一些关于接口目的的问题。我看到的答案大致有两种类型:



1.一些答案只能说明界面是什么。

2.其他答案会说接口允许你从多个类继承,或者通过结构而不是类继承。



据我所知,实现接口确实并没有真正从接口继承任何东西,因为你必须从头开始编写你应该从接口继承的所有内容。由于界面只有签名,所以除了标题之外你真的没有任何东西可以继承。



因为(据我所知)你只继承了接口但没有别的,也许接口的真正价值在于它可以将一组类标记为具有一些通用功能?



注意:我之前在Stackoverflow中问过这个问题,但我只得到那些可能不理解这个问题的人的嘲讽和不文明的回答。即使你不尊重这个问题,也要比这更好,不要使用不文明的语言。我对这里所有体面的人都表示最崇高的敬意。



我的尝试:



C#接口,例如ICommand和INotifyPropertyChanged。

I am new to programming. I have seen some past questions about the purpose of interfaces. The answers I have seen are broadly two types:

1. Some answers will just explain what an interface is.
2. Other answers will say that an interface allows you to inherit from multiple classes, or to inherit by a structure rather than a class.

As far as I understand, implementing an interface does not really inherit anything from the interface because you have to write from scratch everything that you are supposedly inheriting from the interface. Since the interface has only signatures, it really has nothing you can inherit other than the title.

Since (as far as I know) you only inherit the name of the interface but nothing else, perhaps the real value of the interface is that it can mark a group of classes as having some common functionality?

Note: I asked this question before in "Stackoverflow" but I got only mocking and uncivil responses from people who probably did not understand the question. Please be better than that and refrain from uncivil language, even if you don't respect the question. My greatest respect to all the decent people here.

What I have tried:

C# interfaces such as ICommand and INotifyPropertyChanged.

推荐答案

// Interface 

public interface ILogger
{
    public void Log(string msg);
}

// 'Concrete' classes 

public class FileLogger : ILogger
{
      // TODO : Implement Log method to File, Possibly File Spec From Ctor
}

public class TextBoxLogger : ILogger
{
      // TODO : Implement Log method to TextBox, Possibly TextBox Name From Ctor
}

public class DatabaseLogger : ILogger
{
      // TODO : Implement Log method to Database, Possibly Database Connection From Ctor
}





所以,你ave接口,ILogger,说,任何实现我的类必须实现Log(string msg);因为这是接口定义指定的'合同'



..无论你是否使用FileLogger,TextBoxLogger,DatabaseLogger,一旦你有这样的实例对象,你只调用Log(some message);



也许有帮助



So, you have the interface, ILogger, that says, any class that implements me MUST implement Log(string msg); because that's the 'contract' specified by the Interface definition

.. irrespective of whether you're using the FileLogger, TextBoxLogger, DatabaseLogger, once you have an instance of those objects, you only ever call Log("some message");

maybe that helps


这篇关于接口只是将类标记为具有通用功能的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 04:36