我们为什么能写
public int RetInt
{
get;set;
}
代替
public int RetInt
{
get{return someInt;}set{someInt=value;}
}
两者有什么区别?
最佳答案
此功能称为 Auto implemented properties并在 C# 3.0 中引入
In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. They also enable client code to create objects. When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.
class Customer
{
// Auto-Impl Properties for trivial get and set
public double TotalPurchases { get; set; }
public string Name { get; set; }
public int CustomerID { get; set; }
针对您的问题
What is the difference between the two?
在你的情况下,没有。由于您在设置或检索值时没有做任何事情,但假设您想要进行一些验证或想要执行其他类型的检查:
private int someInt;
public int RetInt
{
get
{
if (someInt > 0)
return someInt;
else
return -1;
}
set { someInt = value; } // same kind of check /validation can be done here
}
以上不能用自动实现的属性来完成。
您可以看到不同之处的另一件事是在初始化自定义类类型属性时。
如果你有 MyClass
列表
然后在 Normal 属性的情况下,除了构造函数之外,它的支持字段可以被初始化/实例化。
private List<MyClass> list = new List<MyClass>();
public List<MyClass> List
{
get { return list; }
set { list = value; }
}
如果是自动实现的属性,
public List<MyClass> SomeOtherList { get; set; }
您只能在构造函数中初始化SomeOtherList
,不能在Field 级别执行此操作。
关于c# - C# 中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14559909/