什么是C#构造对象的首选方式?构造函数的参数和属性? [英] What is the preferred way of constructing objects in C#? Constructor parameters or properties?

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

问题描述

我想知道,什么是构造一个新的对象在C#中的首选方式。

I was wondering, what is the preferred way to construct a new object in C#?

以一个Person类:

Take a Person class:

public class Person 
{
    private string name;
    private int age;

    //Omitted..
}



我应该创建它的使用方法:

Should I create it to use:

New Person("name", 24);

New Person() { Name = "name", Age = 24 };



这是否只是一种品味的问题或者是有一个很好的理由使用了另一种?

Is it just a matter of taste or is there a good reason to use one over the other?

我可以想像,一个人应该只使用在构造函数中所需的字段和可选字段不是作为构造函数的参数,但通过使用属性。

I can imagine that one should only use the required fields in the constructor and optional fields not as constructor parameters but by using properties.

我是正确的吗?

推荐答案

的首选方式取决于你的设计。

The preferred way depends on your design.

构造属性是你的对象要求才能被正确构建项目。也就是说,对象应该有任何的属性,以初始化需要在构造函数(你通常不想部分intialized对象调用构造函数,除非你正在创建一个工厂或生成器模式和后构造函数从所有但工厂/生成器)是隐藏的。

Constructor properties are for items that your object requires in order to be correctly constructed. That is to say, any properties the object should have in order to be initialized need to be in the constructor (you don't usually want a partially intialized object after the constructor is called unless you're creating a factory or builder pattern and the constructor is hidden from all but the factory/builder).

属性intializers是最好的附加配置由您的特定用例必需的,但不需要构造后要考虑的对象初始化。

Property intializers are best for additional configuration after a constructor that is required by your particular use case but is not required for the object to be considered initialised.

例如,你可以有一个代表一个人的对象。一个人需要一个名称和被初始化的年龄,但他们住在该地址是可选配置。所以,姓名和年龄是构造函数的参数,而该地址是一个读/写属性。

For example, you could have an object that represents a person. A person needs a name and an age to be initialised, but the address they live at is an optional configuration. So, the name and age are constructor parameters, and the address is a read/write property.

Person johnDoe = new Person("John Doe", 24) { Address = "42 Adams Street" };

这篇关于什么是C#构造对象的首选方式?构造函数的参数和属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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