说我有一些代码如下:
public class Person
{
public string Name, Job;
public int Age;
public Person(string name, int age, string job)
{
Name = name;
Age = age;
Job = job;
}
}
是否有更短的方法来做而不是做" [Variable] = [Argument]
"每个论点?
答案 0 :(得分:3)
由于您的属性是公共的,您可以在实例化后立即设置它们:
var person = new Person
{
Name = value1,
Age = value2,
Job = value3
}
班级本身将是:
public string Name, Job {get; set;}
public int Age {get; set;}
public Person()
{
}
P.S。不要使用公共领域
答案 1 :(得分:1)
由于没有检查,为什么不在构造函数中省略参数,将字段转换为属性,并将其init保留在调用代码中?
Person person = new Person()
{
Name = "elseytd",
Age = 24,
Job = Jobs.Programmer
};