最好的方式来创建对象 [英] best way to create object

查看:134
本文介绍了最好的方式来创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是非常愚蠢和基本的问题,但我试图谷歌它,但不能找到满意的答案,

This seems to be very stupid and rudimentary question, but i tried to google it, but couldn't a find a satisfactory answer,

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public Person(){}
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
    //Other properties, methods, events...
}


$ b b

我的问题是如果我有这样的类,什么是最好的方式来创建一个对象?

My question is if i have class like this, what is the best way to create an object?

Person p=new Person("abc",15)

>

OR

Person p=new Person();
p.Name="abc";
p.Age=15;

这两种方法有什么区别,什么是创建对象的最佳方式?

What is the difference between these two methods and what is the best way to create objects?

推荐答案

您必须了解您是否需要一个不可变的对象。

You have to understand if you need an immutable object or not.

如果你在类中加入 public 属性,你的代码中每一个实例的状态都可以改变。所以你的类可能是这样的:

If you put public properties in your class, the state of every instance can be changed at every time in your code. So your class could be like this:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public Person(){}
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
    //Other properties, methods, events...
}


$ b b

在这种情况下,具有 Person(string name,int age)构造函数不太有用。

第二个选项是实现不可变的类型。例如:

The second option is to implement an immutable type. For example:

public class Person
{
    public string Name { get; private set; }
    public int Age { get; private set; }

    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
    //Other properties, methods, events...
}


$ b b

现在你有一个构造函数允许在创建时设置实例的状态一次。注意,现在属性的setters是 private ,所以你不能在你的对象被实例化后改变状态。

Now you have a constructor that permits to set the state for the instance, once, at creation time. Note that now setters for properties are private, so you can't change the state after your object is instantiated.

最好的做法是每次都将类定义为不可变。要了解不可变类的优点,我建议您本文< a>。

A best practice is to define classes as immutable every time is possible. To understand advantages of immutable classes I suggest you this article.

这篇关于最好的方式来创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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