,应注意以下...设置变量定义VS
//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较短,但在编译期间效率较低。
模式2是一个堆栈溢出。 – SLaks
@SLaks ..给予这个网站的名称似乎是适当的? :P –
标记为以下副本:http://stackoverflow.com/questions/24551/best-practice-initialize-class-fields-in-constructor-or-at-declaration请阅读那里的评论/答案。 – lahsrah