C# 破解 : low level difference between interface and abstract class

标签 c# oop inheritance interface

这是一个关于 C# 基础的哲学问题:我想知道一个接口(interface)可以被完全抽象的类模拟到什么程度。假设我们有以下接口(interface):

public interface INativeInterface
{
    void PerformAction();
    String Property { get; set; }
}

和下面的抽象类:

public abstract class ISimulatedInterface
{
    public abstract void PerformAction();
    public abstract String Property { get; set; }
}

他们有很多共同点,不是吗?我知道的区别是:

  • 多重继承不适用于抽象类
  • 显式实现对抽象类不起作用

是否可以使用反射或类似的方式跳过这些限制?

我意识到接口(interface)和抽象类在根中是不同的:接口(interface)声明了一个条件“可以表现得像”,抽象类-“是一种”,但即使这似乎如此接近,以至于必须讨论这些实体之间的低级差异。这个问题甚至可以听起来像“你会怎么做才能用 C++ 制作接口(interface)”。

最佳答案

Can these restrictions be skipped by using reflection or something like this?

没有。抽象类和接口(interface)是公共(public)语言运行时级别的不同概念。因此在 C# 中是不可能的,因为最终受限于 CLR 的边界。

I am wondering how close an interface may be simulated by fully abstract class.

这是可行的,但需要来自底层执行环境(无论是物理的还是托管的)的支持(或“允许”)。

过去我设计了一种完全用抽象类代替接口(interface)的语言。是的,它确实支持此类“接口(interface)”的多重继承。然而,实现的特殊性可能不值得付出努力。主要的“低级差异”是继承抽象类的内部嵌入式实例必须保留在实现类的实例中,并且必须维护 this 指针链。不用说,这是一次愉快的经历:-)

关于C# 破解 : low level difference between interface and abstract class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20887715/

相关文章:

c# - 从将其结果传递给 Action<T> 参数的方法返回 Task<T>

python - 在数值工作中混合使用 numpy 和 OO

javascript - 快速 Javascript 继承 : Understanding __proto__

c# - RavenDB 中的自左连接

c# - 反序列化 json 数组

c++ - C++中的结构和类有什么区别?

c++ - 什么时候调用继承的Constructor代码

派生类中的 C++ 纯虚函数实现

c# - 如何从服务器端代码反序列化 JSON

python - 如何在基类方法中使用派生类变量