创建对象最好的方式最好的、对象、方式

2023-09-03 10:34:21 作者:失心

这似乎是非常愚蠢的,基本的问题,但我试图谷歌,但也没有找到满意的答案,

 公共类Person
{
    公共字符串名称{;组; }
    公众诠释年龄{获得;组; }
    公众人物(){}
    公众人物(字符串名称,诠释年龄)
    {
        名称=名称;
        年龄=岁;
    }
    //其他属性,方法,事件...
}
 

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

 者P =新的Person(ABC,15)
 
JavaScript 创建对象 方法一览与最佳实践

 者P =新的Person();
p.Name ='ABC';
p.Age = 15;
 

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

解决方案

您要明白,如果你需要的一成不变的对象或不是。

如果你把公开属性在类中,每个实例的状态可以在每一次在你的code改变。所以,你的类可以是这样的:

 公共类Person
{
    公共字符串名称{;组; }
    公众诠释年龄{获得;组; }
    公众人物(){}
    公众人物(字符串名称,诠释年龄)
    {
        名称=名称;
        年龄=岁;
    }
    //其他属性,方法,事件...
}
 

在这种情况下,有一个人员(字符串名称,诠释岁)构造不那么有用。

第二个选择是实施的一成不变的类型。例如:

 公共类Person
{
    公共字符串名称{;私定; }
    公众诠释年龄{获得;私定; }

    公众人物(字符串名称,诠释年龄)
    {
        名称=名称;
        年龄=岁;
    }
    //其他属性,方法,事件...
}
 

现在你有一个构造函数,允许设置状态的情况下,一次,在创建时。需要注意的是,现在制定者的属性私人,所以你不能改变你的对象实例化后的状态。

一个最好的做法是定义类作为不可改变每次都是可能的。要了解一成不变的类的优势,我建议你这篇文章。

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...
}

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.

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...
}

In this case, having a Person(string name, int age) constructor is not so useful.

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...
}

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 best practice is to define classes as immutable every time is possible. To understand advantages of immutable classes I suggest you this article.