接口/类 [英] interface/class

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

问题描述

我什么时候应该使用接口而不是类?使用接口的有用之处

when should i use interface instead of class?what is d usefullness of using interface

推荐答案

接口允许您指定继承对象必须实现但没有实现的东西您需要自己提供任何实现.

使用用于排序的IComparable接口,Microsoft不可能知道如何对您的类进行排序,但是通过提供自己的实现,他们的任何使用IComparable参数的方法都可以对其进行排序!
An interface allows you to specify things that inheriting objects must implement but without you needing to provide any implementation yourself.

Take the IComparable interface used for sorting, there is no way Microsoft could possibly know how to sort you class, but by you providing your own implementation, any of their methods that take an IComparable parameter will be able to sort it!


您的意思是用法.赖特?

这是一个简短的解释:

接口 定义了 合同 派生类应实现.

这意味着它定义了类和/或结构应实现的方法(其签名).

此外,C#/.Net允许多个接口但可以继承单个类.

假设您有一个LogSystem.该系统应该写一些东西.

所以:
You mean usage. Wright?

Here''s a very short expalation:

A Interface defines a contract that the
derived class should implement.

Meaning it defines the methods(their signatures) that a class and/or struct should implement.

Also C#/.Net allows for multiple Interface but single class inheritance.

Supose you have a LogSystem. That system should write something.

So:
interface IWrite
{
    public void Write();
}



上面的接口为这些类定义了一个契约,在这种情况下,契约是一个返回null的单一方法.

现在您可以拥有一个WriteToLog类,WriteToOutput(例如console),
到数据库.

但是所有这些类都实现了IWrite接口.



The interface above defines a contract for the classes.It''s contract it''s a single method in this case that returns null.

Now you could have like a WriteToLog class, WriteToOutput(e.g. console),
to a DB.

but all of this classes Implement the IWrite interface.

public class WriteToLog: IWrite{
    public void Write(){
       //implement it here
    }
}

public class WriteToConsole: IWrite{
    public void Write(){
       //implement it here
    }
}


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

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