【发布时间】:2017-10-20 07:29:11
【问题描述】:
在 C sharp 中,如果我们有 2 个接口,具有相同的签名方法,我们可以在一个类中实现它们,方式如下:
interface A
{
void doStuff();
}
interface B
{
void doStuff();
}
class Test : A, B
{
void A.doStuff()
{
Console.WriteLine("A");
}
void B.doStuff()
{
Console.WriteLine("A");
}
}
如果我们把它翻译成 Kotlin,我们就有
interface A
{
fun doStuff()
}
interface B
{
fun doStuff()
}
class Test : A, B
{
override fun doStuff() {
println("Same for A b")
}
}
fun main(args: Array<String>)
{
var test = Test();
test.doStuff() //will print Same for A b"
var InterfaceA:A = test
var InterfaceB:B = test
InterfaceA.doStuff()//will print Same for A b"
InterfaceB.doStuff()//will print Same for A b"
}
所以,我的问题是,我该怎么做 给每个接口一个不同的实现,如 C sharp 示例中的?。 **注意:我已经阅读了https://kotlinlang.org/docs/reference/interfaces.html 上的文档,有一个类似的例子,
interface A {
fun foo() { print("A") }
}
interface B {
fun foo() { print("B") }
}
class D : A, B {
override fun foo() {
super<A>.foo()
super<B>.foo()
}
}
这里,foo是在每个接口中实现的,所以在D中实现时,它只是调用接口中定义的实现。但是我们如何在 D 中定义不同的实现呢?
【问题讨论】:
-
请重新格式化您的示例代码(添加缩进)
-
现在好点了吗@voddan?