sách gpt4 ai đã đi

giao diện - triển khai một giao diện không tĩnh bên trong

In lại 作者:行者123 更新时间:2023-12-02 11:26:20 25 4
mua khóa gpt4 Nike

我想从包装类外部实例化一个内部非静态接口(interface)。

Liệu điều này có thể thực hiện được không?

考虑以下代码:

shared class AOuterClass() {
Integer val = 3;
shared interface AInterface {
shared Integer val => outer.val;
}
}

void test() {
AOuterClass o = AOuterClass();
object impl satisfies ???.AInterface{}
}

Tôi nghĩ object impl 满足 o.AInterface{} 是我合理的直觉,但编译器不允许这样做。

1 Câu trả lời

在像您这样的情况下这是不可能的。

ceylon 规范说 ( section 4.5.4 Class Inheritance ):

A subclass of a nested class must be a member of the type that declares the nested class or of a subtype of the type that declares the nested class. A class that satisfies a nested interface must be a member of the type that declares the nested interface or of a subtype of the type that declares the nested interface.

因此,您只能满足声明类或其子类中的嵌套接口(interface)。类似的语言也可用于通过新接口(interface)扩展嵌套接口(interface)。

这并没有直接提到sự vật声明,但这些只是类定义的快捷方式,稍后将在Anonymous classes中详细说明。 :

The following declaration:

shared my object red extends Color('FF0000') {
string => "Red";
}

Is exactly equivalent to:

shared final class \Ired of red extends Color {
shared new red extends Color('FF0000') {}
string => "Red";
}

shared my \Ired red => \Ired.red;

Where \Ired is the type name assigned by the compiler.

因此,这也涵盖了您的对象声明。

你可以做什么(我没有测试过):

AOuterClass.AInterface test(){
object o extends AOuterClass() {
shared object impl satisfies AInterface{}
}
return o.impl;
}

当然,这不适用于现有的 AOuterClass 对象,仅适用于新创建的对象。看到这允许访问对象的私有(private)值,这似乎是一件好事。

关于interface - 实现内部非静态接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45358498/

25 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com