C# 使用带分号的基本构造函数

问题描述 投票:0回答:2

在 C# 中创建构造函数时,引用继承类的超级构造函数,为什么我需要使用大括号,而不是选择用分号终止语句?

我想到了这个问题,因为我目前有一个抽象类,继承该类可以轻松地从执行的命令返回结果。

例如:

 abstract class CommandResult<T> {
    protected CommandResult() { }

    protected CommandResult(string msg) : this() {
        Message = msg;
    }

    protected CommandResult(string msg, T result) : this(msg) {
        Result = result;
    }

    protected CommandResult(T result) : this() {
        Result = result;
    }
 }

将是我的抽象类。 在引用它的类中,它们目前看起来如下所示:

 public class CommandIntResult: CommandResult<int> {

    public CommandIntResult() { }

    public CommandIntResult(string msg) : base(msg) { }

    public CommandIntResult(string msg, int result) : base(msg, result) { }

    public CommandIntResult(int result) : base(result) { }

}

构造函数体内没有任何逻辑。 需要括号而不是选择以分号结尾的原因是什么?

public CommandIntResult(string msg, int result): base(msg, result);
c# syntax constructor semantics
2个回答
3
投票

在方法声明的上下文中,

;
并不意味着“这是一个空方法”。

abstract
方法上,这意味着“没有方法体”。

extern
方法上,这意味着实际代码位于其他地方。

对于属性 getter 和 setter,这意味着“该方法的代码是自动生成的”。

如果你想写一个方法体,已经有一种写法了,而且只长一个字符 -

{}


0
投票

您在 2017 年的这个问题中提出的要求现在在 C# 12 中是允许的。奇怪的是,我在文档中找不到任何官方提及的内容(!),但我注意到它是因为用户要求 Roslynator 添加分析器建议它(RCS1251)。现在,您可以在 C# 中同时拥有空构造函数和整个空类型,它们只是以

;
而不是
{ }
终止。

© www.soinside.com 2019 - 2024. All rights reserved.