c# - 接口(interface)实例

标签 c# .net interface

我是 C#.net 的新手,很惊讶可以像这样创建接口(interface)的实例

Iinterface myDimensions = (Iinterface) myBox;

如何为这种类型的语句分配内存?内存分配在堆上吗?

任何人都可以给出使用这种类型的实例化的任何情况。

A class that implements an interface can explicitly implement a member of that interface. When a member is explicitly implemented, it cannot be accessed through a class instance, but only through an instance of the interface.

为什么要在语言中强制执行这样的约束?

谢谢,

最佳答案

在回答您的第一个问题之前,我注意到您在这里有两个问题。将来,当您有两个问题时,考虑在 Stack Overflow 上问两个单独的问题。您可能已经注意到,当您将两个问题合二为一时,第二个问题通常会被几乎所有人忽略。

I was surprised to know that instances of an interface can be created like

Iinterface myDimensions = (Iinterface) myBox; 

How is memory allocated for this type of statement? Is the memory allocated on heap?

正如其他人所指出的,这不是必然创建实现该接口(interface)的类型的实例。每个人似乎都在匆忙告诉您引用转换不分配内存时忘记了,装箱转换确实分配内存。如果 myBox 是结构类型,那么这将在堆上为“包装器”分配内存并复制包装器中的值。然后包装器实现接口(interface)。

继续第二个问题:

A class that implements an interface can explicitly implement a member of that interface. When a member is explicitly implemented, it cannot be accessed through a class instance, but only through an instance of the interface. Why is such a constraint enforced in the language?

显式接口(interface)实现的目的是使一个类能够实现一个特定的接口(interface),而不需要那些方法出现在它们不需要的地方。例如,假设您有:

class MyConnection : IDisposable
{
    public void OpenConnnection() { ... }
    public void CloseConnection() { ... }
    public void Dispose() { ... CloseConnection(); ... }
}

如果处理打开的连接与关闭连接相同,那么您可能不希望通过以下方式混淆您的用户:(1) 有两个方法做同样的事情,或者 (2) 方法 OpenConnection 与一个配对不明显的名称,例如 Dispose。通过使您能够使 Dispose 变得“不可见”,除非对象被转换为 IDisposable,这样您就可以让您的用户更轻松地发现正确的事情。

另一种情况是当您有两个同名接口(interface)时:

interface IFoo { void M(); }
interface IBar { void M(); }

现在如何创建一个同时实现 IFoo 和 IBar,但对两个 M 方法有不同实现的类 C?如果您想要两个不同的主体,则必须对其中一个或两个使用显式实现。

关于c# - 接口(interface)实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3729461/

相关文章:

c# - 捆绑链接的 JavaScript 文件

c# - 也许在 Linq 中找到了一个功能。具有多个字段的 Groupby

c# - 正确处理和删除对 UserControl 的引用,以避免内存泄漏

c# - 为什么静态类不能有非静态方法和变量?

c# - HttpStatusCode 枚举没有 507 (InsufficientStorage)

reflection - 验证一个接口(interface)是否满足另一个接口(interface)

c# - 使用 LINQ 从域列表中删除子域

.net - 找不到使用带有 .NET 5 顶级调用的反射的 Main 方法

java - 转换派生 Java 接口(interface)的集合(泛型)

java - 我可以在java中为 'Interface'而不是 'Class'定义 'Object'吗?