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

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

问题描述

public void Finalise()
    ProcessFinalisation(true);

不能编译,但版本正确:

Doesn't compile, but the correct version:

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

编译良好(当然).

如果下面的代码只有一行时,如果允许 if 没有括号:

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天全站免登陆