C#在类构造函数中分配类属性有什么好处? [英] C# Is there any benefit to assigning class properties in the class constructor?

查看:117
本文介绍了C#在类构造函数中分配类属性有什么好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我有一个像这样的课程:

namespace Sample
{
     public Class TestObject
     {
          private Object MyAwesomeObject = new MyAwesomeObject();
     }
}

设置它是否有任何好处,以便像这样在构造函数中设置属性?

namespace Sample
{
     public Class TestObject
     {
          private Object MyAwesomeObject;

          public TestObject()
          {
                MyAwesomeObject = new MyAwesomeObject()
          }
     }
}

解决方案

两者(几乎)相同.

当您内联定义初始化程序时:

private Object MyAwesomeObject = new MyAwesomeObject(); 

这将在类构造函数代码之前发生.这通常更好,但确实有一些限制.

在构造函数中进行设置可让您使用构造函数参数初始化成员.通常,这是使您的班级成员获得更多信息所必需的.

此外,当在构造函数中设置值时,可以在静态上下文中使用类数据,而内联方法则无法做到这一点.例如,如果要使用表达式树初始化某些内容,则通常需要在构造函数中,因为表达式树处于静态上下文中,不允许在嵌入式成员初始化程序中访问您的类成员. /p>

For instance, if I have a class like this:

namespace Sample
{
     public Class TestObject
     {
          private Object MyAwesomeObject = new MyAwesomeObject();
     }
}

Is there any benefit to set it up so that the property is set in the constructor like this?

namespace Sample
{
     public Class TestObject
     {
          private Object MyAwesomeObject;

          public TestObject()
          {
                MyAwesomeObject = new MyAwesomeObject()
          }
     }
}

解决方案

The two are (nearly) identical.

When you define the initializer inline:

private Object MyAwesomeObject = new MyAwesomeObject(); 

This will happen prior to the class constructor code. This is often nicer, but does have a couple of limitations.

Setting it up in the constructor lets you use constructor parameters to initialize your members. Often, this is required in order to get more information into your class members.

Also, when you setup values in your constructors, you can use your class data in a static context, which is not possible to do with inlined methods. For example, if you want to initialize something using an expression tree, this often needs to be in a constructor, since the expression tree is in a static context, which will not be allowed to access your class members in an inlined member initializer.

这篇关于C#在类构造函数中分配类属性有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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