观察以下...
//pattern 1
public class Cheesesteak
{
public string bread {get; private set}
public string cheese {get; private set}
public Cheesesteak()
{
bread = "Amoroso";
cheese = "Cheez Whiz";
}
}
//pattern 2
public class Cheesesteak
{
public string bread
{
get {return bread;}
set
{
bread = "Amoroso";
}
}
public string cheese
{
get {return cheese;}
set
{
cheese = "Cheez Whiz";
}
}
public Cheesesteak() {}
}
这是一个好奇的问题。在“集合”的定义中设置变量而不是在构造函数中声明它们是否有任何优势或特殊原因?我最初的猜测是模式 1 更短,但在编译期间效率更低。