将 return 与方法内联一起使用

Using return with method inline

我想用 switch 块内联一个方法。

如果我在 switch 语句中使用 return,它会中断 ParentMethod 的执行吗?

void ParentMethod()
{
    InliningMethod(myEnum.SomeValue);

    //do some after inline for test case
    Console.WriteLine("Will this have been writed?"); 
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
void InliningMethod(MyEnum value)
{
    switch(myEnum)
    {
        case MyEnum.SomeValue:
            return; //will it have been moved in ParentMethod?
        default: break;       
    }
    //do some
}

内联并不意味着代码只是被复制过来。编译器会正确处理,return 只退出它所在的方法,无论编译器稍后是否内联它。

内联方法只是一种用更少的代码编写方法的风格,它不会改变执行原理。因此,"return statement" inside 内联方法不会破坏父方法。