C#中的构造方法与对象初始化方法的优先级 [英] Constructor vs Object Initializer Precedence in C#

查看:179
本文介绍了C#中的构造方法与对象初始化方法的优先级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近一直在用C#学习对象初始化器,但是现在我想知道当它与构造函数冲突时它是如何工作的.

I've been learning the object initializer in C# recently, but now I'm wondering how it works when it conflicts with the constructor.

public class A
{
    public bool foo { get; set; }
    public A()
    {
        foo = true;
    }
    public A(bool bar)
    {
        foo = bar;
    }
}

尝试此操作会发生什么?

What happens when I try this?

public class B
{
    a = A() {foo = false};
    b = A(true) {foo = false};
}

构造函数中的默认值是使bool开始为true且可以更改的好方法吗?

Is a default in the constructor a good way to have a bool that starts true and can be changed?

public A(bar=true)
{
    foo = bar;
}

推荐答案

来自文档 a>:

编译器通过首先访问对象初始化器来处理对象初始化器 默认实例构造函数,然后处理成员 初始化.

The compiler processes object initializers by first accessing the default instance constructor and then processing the member initializations.

这意味着在最简单的情况下(命名对象初始化),它基本上是调用默认构造函数然后调用属性setter的简写形式(或语法糖).对于匿名类型,实际上需要这种初始化,而不仅仅是糖.

This means that in the simplest case (named object initialization) it is basically shorthand (or syntactic sugar) for calling the default constructor and then calling the property setter(s). In the case of anonymous types this kind of initialization is actually required and not mere sugar.

对于问题的第二部分:这更多的是样式问题,但是如果您具有关键属性,那么我将不会创建具有默认值的构造函数.使客户端代码显式设置值.我也不确定为什么要这样做:b = A(true) {foo = false};是个好主意,除非您参加了代码混淆竞赛.

For the 2nd part of your question: It's more of a matter of style but if you have a crucial property I would not create a constructor with a default value. Make the client code set the value explicitly. I'm also not sure why doing something like this: b = A(true) {foo = false}; would be a good idea unless you're in a code obfuscation contest.

请谨慎一点:

...如果默认构造函数在类中声明为私有, 需要公共访问的对象初始化程序将失败.

... if the default constructor is declared as private in the class, object initializers that require public access will fail.

这篇关于C#中的构造方法与对象初始化方法的优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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