C# 创建对象的最佳方式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14747095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:54:18  来源:igfitidea点击:

best way to create object

c#.netoopconstructorinstance

提问by DevT

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?

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

采纳答案by davioooh

Decide if you need an immutableobject or not.

决定是否需要不可变对象。

If you put publicproperties 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属性放入类中,则可以在代码中每次更改每个实例的状态。所以你的班级可能是这样的:

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 that case, having a Person(string name, int age)constructor is not so useful.

在这种情况下,拥有一个Person(string name, int age)构造函数就没那么有用了。

The second option is to implement an immutabletype. 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 sets 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.

现在您有一个构造函数,可以在创建时为实例设置一次状态。请注意,现在属性的 setter 是private,因此您无法在实例化对象后更改状态。

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

如果可能,最佳实践是每次都将类定义为不可变的。要了解不可变类的优点,我建议您阅读这篇文章

回答by xlecoustillier

There's not really a best way. Both are quite the same, unless you want to do some additional processing using the parameters passed to the constructor during initialization or if you want to ensure a coherent state just after calling the constructor. If it is the case, prefer the first one.

真的没有最好的办法。两者完全相同,除非您想使用在初始化期间传递给构造函数的参数进行一些额外的处理,或者如果您想确保在调用构造函数后立即保持一致状态。如果是这样,请选择第一个。

But for readability/maintainability reasons, avoid creating constructors with too many parameters.

但出于可读性/可维护性的原因,请避免创建具有过多参数的构造函数。

In this case, both will do.

在这种情况下,两者都可以。

回答by Paul Alan Taylor

Really depends on your requirement, although lately I have seen a trend for classes with at least one bare constructor defined.

确实取决于您的要求,尽管最近我看到了至少定义了一个裸构造函数的类的趋势。

The upside of posting your parameters in via constructor is that you know those values can be relied on after instantiation. The downside is that you'll need to put more work in with any library that expects to be able to create objects with a bare constructor.

通过构造函数发布参数的好处是您知道在实例化后可以依赖这些值。缺点是您需要在任何希望能够使用裸构造函数创建对象的库中投入更多工作。

My personal preference is to go with a bare constructor and set any properties as part of the declaration.

我个人的偏好是使用裸构造函数并将任何属性设置为声明的一部分。

Person p=new Person()
{
   Name = "Han Solo",
   Age = 39
};

This gets around the "class lacks bare constructor" problem, plus reduces maintenance ( I can set more things without changing the constructor ).

这解决了“类缺少裸构造函数”的问题,并减少了维护(我可以在不更改构造函数的情况下设置更多内容)。

回答by roast_soul

If you think less code means more efficient, so using construct function is better. You also can use code like:

如果你认为更少的代码意味着更高的效率,那么使用构造函数会更好。您还可以使用以下代码:

Person p=new Person(){
Name='abc',
Age=15
}

回答by Hugo Mota

In my humble opinion, this is just a matter of deciding if the arguments are optional or not. If an Person object shouldn't (logically) exist without Name and Age, they should be mandatory in the constructor. If they are optional, (i.e. their absence is not a threat to the good functioning of the object), use the setters.

在我看来,这只是决定参数是否可选的问题。如果没有 Name 和 Age 的 Person 对象(逻辑上)不应该存在,则它们应该在构造函数中是强制性的。如果它们是可选的(即它们的缺失不会威胁到对象的良好运行),请使用 setter。

Here's a quote from Symfony's docs on constructor injection:

这是 Symfony 文档中关于构造函数注入的引用:

There are several advantages to using constructor injection:

  • If the dependency is a requirement and the class cannot work without it then injecting it via the constructor ensures it is present when the class is used as the class cannot be constructed without it.
  • The constructor is only ever called once when the object is created, so you can be sure that the dependency will not change during the object's lifetime.

These advantages do mean that constructor injection is not suitable for working with optional dependencies. It is also more difficult to use in combination with class hierarchies: if a class uses constructor injection then extending it and overriding the constructor becomes problematic.

使用构造函数注入有几个优点:

  • 如果依赖是必需的,并且类没有它就不能工作,那么通过构造函数注入它可以确保在使用类时它存在,因为没有它就不能构造类。
  • 构造函数只在创建对象时调用一次,因此您可以确保依赖项在对象的生命周期内不会改变。

这些优点确实意味着构造函数注入不适合处理可选依赖项。与类层次结构结合使用也更加困难:如果一个类使用构造函数注入,那么扩展它并覆盖构造函数就会成为问题。

(Symfony is one of the most popular and respected php frameworks)

(Symfony 是最流行和最受尊敬的 php 框架之一)

回答by Chimmy

Or you can use a data file to put many person objects in to a list or array. You do need to use the System.IO for this. And you need a data file which contains all the information about the objects.

或者,您可以使用数据文件将多个 person 对象放入列表或数组中。为此,您确实需要使用 System.IO。并且您需要一个包含有关对象的所有信息的数据文件。

A method for it would look something like this:

它的方法如下所示:

static void ReadFile()
{
    using(StreamWriter writer = new StreamWriter(@"Data.csv"))
    {
        string line = null;
        line = reader.ReadLine();
        while(null!= (line = reader.ReadLine())
                {
                    string[] values = line.Split(',');
                    string name = values[0];
                    int age = int.Parse(values[1]);
                }
        Person person = new Person(name, age);
    }
}

回答by KIRAN RAJ SADULA

Depends on your requirment, but the most effective way to create is:

取决于您的要求,但最有效的创建方法是:

 Product obj = new Product
            {
                ID = 21,
                Price = 200,
                Category = "XY",
                Name = "SKR",
            };