【发布时间】:2017-03-23 20:26:36
【问题描述】:
我目前正在定义自定义对象属性如下:
private int count;
public int Count
{
get { return count; }
set { Count = value; }
}
我的第一部分问题是定义类似和类似的字段之间有什么区别:
private int count;
public int Count {get; set;}
除非你想像这样检查值:
private int count;
public int Count
{
get { return count; }
set
{
if (value >= 0)
{
count = value;;
}
else MessageBox.Show("Value is negative", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
第二部分是有没有更好的方法在 C# 中定义对象属性?
【问题讨论】:
-
没有比
public int Count {get; set;}更好的了 -
我投票决定将此问题作为题外话结束,因为所有这些都在官方文档中进行了解释。先咨询msdn.microsoft.com/en-us/library/x9fsa0sw.aspx