Exect支持多重继承,为什么在没有方法定义时使用接口? [英] Exect for supporting multiple inheritance, why to use interface when they have no method definition ?

查看:122
本文介绍了Exect支持多重继承,为什么在没有方法定义时使用接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是.NET新手。我很困惑为什么在只有方法声明而不是实现时使用接口?

使用接口的目的是什么,而不仅仅是支持多重继承?



我可以在每个类中编写自己的方法。为什么需要实现特定的接口?



假设为了释放对象,我必须实现IDisposable接口&需要提供Dispose()方法的实现细节。相反,我可以编写自己的方法来释放对象。我为什么要实现IDisposable接口?



我尝试过:



我可以在每个类中单独编写自己的方法,而不是实现特定的接口。

I am new to the .NET. I am confused on why to use interface when they have only method declaration and not the implementation ?
What is the purpose of using interface than just supporting multiple inheritance ?

I can write my own methods in each class. Why there is need to implement particular interface ?

Let's say, for releasing objects, I have to implement IDisposable interface & need to provide implementation details for Dispose() method. Instead, I can write my own method to free the objects. Why should I implement IDisposable interface ?

What I have tried:

I may write own methods separately in each class instead of implementing particular interface.

推荐答案

如果你用自己的方法编写一个类来释放资源;



If you write a class with its own method to release resources;

public class MyClass
{
    public void CleanUp()
    {
    }
}





然后你可以编写使用这个对象的代码





then you can write code that uses this object

MyClass c = new MyClass()
c.SomeMethod();
c.CleanUp();





这很棒,但你只能编写你知道的关于CleanUp的代码,其他课程不知道那个方法。因此,假设您创建了一个MyClass实例并且它在堆上,最终.net垃圾收集将运行以处置和清除未使用的对象。垃圾收集如何知道调用您的CleanUp方法?



接口是对象支持方法或功能的保证。此保证允许其他类使用您的类。因此,通过实现IDispose,任何其他需要处理对象的代码都可以这样做,因为接口保证您实现一个名为Dispose的方法,因此任何代码都可以调用类的Dispose方法,因为它知道它存在。



that's great but you can only write that code as you know about CleanUp, other classes don't know about that method. So let's say you create an instance of MyClass and it's on the heap, eventually .net garbage collection is going to run to dispose and get rid of unused objects. How does garbage collection know to call your CleanUp method?

An interface is a guarantee that an object supports a method or functionality. This guarantee allows other classes to use your class. So by implementing IDispose any other code that needs to dispose your object can do so as the interface guarantees you implement a method called Dispose so any code can call the Dispose method of your class as it knows it exists.


简而言之 - 这些类实现一个接口可以使用,因为它们是相同类型(接口的类型),其中只有手工相同的类不能...



为了更全面/更好地理解你应该学习OOP的原理...

也许是一个起点:面向对象编程概念(OOP)和更多内容的介绍 [ ^ ]
In short - those classes implement an interface can be used as they was the of the same type (the type of the interface), where classes that only same by handwork can not...

For a more full/better understanding you should learn the principles of OOP...
Maybe a start point: Introduction to Object Oriented Programming Concepts (OOP) and More[^]


这篇关于Exect支持多重继承,为什么在没有方法定义时使用接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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