Jos*_*ite 5 overriding default-parameters swift swift3
案例:基类 (A) 的函数 (doSomething) 具有默认参数(参数:T = foo),子类 (B) 使用不同的默认参数(参数:T = bar)覆盖该函数。但随后被称为A。
编辑:对原始代码表示歉意,所以实际上发生的事情基本上如下:
class Foo
{
func doSomething(a: String = "123")
{
print(a)
}
}
class Bar: Foo
{
override func doSomething(a: String = "abc")
{
print("Using Bar method body... but not Bar's default a value!")
print(a)
}
}
(Bar() as Foo).doSomething()
// Prints:
// Using Bar method body... but not Bar's default a value!
// 123
Run Code Online (Sandbox Code Playgroud)
它使用函数体但不使用函数默认参数是错误还是预期行为?
它被称为 Foo (或 A),因为你告诉它。因为您正在实例化Bar() as Foo,所以它正是这样做的。
如果你这样做:
Bar().doSomething()
Run Code Online (Sandbox Code Playgroud)
Bar 的方法就是所谓的:
Using Bar method body...
abc
Run Code Online (Sandbox Code Playgroud)
有趣的是,正如您所指出的:
(Bar() as Foo).doSomething()
Run Code Online (Sandbox Code Playgroud)
产量:
Using Bar method body...
123
Run Code Online (Sandbox Code Playgroud)
因为 Bar 被实例化为Foo,(注意强调)Bar 获取 Foo 的默认参数,但仍然执行 Bar 的函数体。
有趣的观察!
| 归档时间: |
|
| 查看次数: |
1591 次 |
| 最近记录: |