重写时是否可以通过在基础 class 方法中使用 'return' 来阻止子方法 运行 ?
Is it possible to prevent a child method from running by using 'return' in the base class method when overriding?
这一定是一个奇怪的问题,但是为什么下面的逻辑不起作用?
public class Base
{
public virtual void Method()
{
return;
}
}
public class Child : Base
{
public override void Method()
{
base.Method(); // If this calls 'return;' here,
print("still here"); // then why this is still running?
}
}
这里的 'return' 会怎样?为什么程序会跳过它?
那里没有return
。就这么简单
A 方法 将执行直到遇到 return
、方法结束或抛出 异常 。在你的情况下没有 return
base.Method(); // do something
print("still here"); // do something else
// end of method, stop doing stuff
其他资源
Methods (C# Programming Guide)
A method is a code block that contains a series of statements. A
program causes the statements to be executed by calling the method and
specifying any required method arguments. In C#, every executed
instruction is performed in the context of a method.
The return keyword also stops the execution of the method. If the
return type is void, a return statement without a value is still
useful to stop the execution of the method. Without the return
keyword, the method will stop executing when it reaches the end of the
code block.
来自 Dave S
的精彩澄清评论
return 只是 return 来自您回调给调用者的函数/方法。 Return 在被调用的函数/方法中不会使调用者本身return。该方法在基础 class 中的事实无关紧要。
这一定是一个奇怪的问题,但是为什么下面的逻辑不起作用?
public class Base
{
public virtual void Method()
{
return;
}
}
public class Child : Base
{
public override void Method()
{
base.Method(); // If this calls 'return;' here,
print("still here"); // then why this is still running?
}
}
这里的 'return' 会怎样?为什么程序会跳过它?
那里没有return
。就这么简单
A 方法 将执行直到遇到 return
、方法结束或抛出 异常 。在你的情况下没有 return
base.Method(); // do something
print("still here"); // do something else
// end of method, stop doing stuff
其他资源
Methods (C# Programming Guide)
A method is a code block that contains a series of statements. A program causes the statements to be executed by calling the method and specifying any required method arguments. In C#, every executed instruction is performed in the context of a method.
The return keyword also stops the execution of the method. If the return type is void, a return statement without a value is still useful to stop the execution of the method. Without the return keyword, the method will stop executing when it reaches the end of the code block.
来自 Dave S
的精彩澄清评论return 只是 return 来自您回调给调用者的函数/方法。 Return 在被调用的函数/方法中不会使调用者本身return。该方法在基础 class 中的事实无关紧要。