只有一个声明的方法为什么需要括号? [英] Why do methods with only one statement need braces?

查看:222
本文介绍了只有一个声明的方法为什么需要括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public void Finalise()
    ProcessFinalisation(true);



不编译,但正确的版本:

Doesn't compile, but the correct version:

public void Finalise()
{
    ProcessFinalisation(true);
}



编译罚款(当然)。

Compiles fine (of course).

如果允许我如果的不带括号时,下面的代码只有一行:

If I am allowed if's without brackets when the following code has only one line:

if(true)
    CallMethod();



为什么同样不允许带有一个后续行的方法呢? ?是否有技术原因

Why is the same not allowed for methods with one following line? Is there a technical reason?

推荐答案

由于C#6.0中,可以声明:

Since C# 6.0 you can declare:

void WriteToConsole(string word) => Console.WriteLine(word)



然后调用它像往常一样:

And then call it as usual:

public static void Main()
{
    var word = "Hello World!";
    WriteToConsole(word);
}

这篇关于只有一个声明的方法为什么需要括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆