可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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?
回答1:
Decide 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 that 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 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.
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.
回答2:
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 ).
回答3:
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.
回答4:
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.
Here's a quote from Symfony's docs on constructor injection:
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)
回答5:
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
}
回答6:
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.
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);
}
}
回答7:
Depends on your requirment, but the most effective way to create is:
Product obj = new Product
{
ID = 21,
Price = 200,
Category = "XY",
Name = "SKR",
};