【发布时间】:2012-11-27 19:21:09
【问题描述】:
可能重复:
Difference between Property and Field in C# .NET 3.5+
Why should I use an automatically implemented property instead of a field?
下面的两个示例完全相同,在类内部和外部具有相同的访问写入... 那么为什么每个人似乎都使用示例 1 而不是示例 2? 我确定我只是遗漏了一些东西,但这一直困扰着我一段时间,我一直无法找到明确的答案。
class SampleClass
{
/// Example 1
/// Shown by online examples.
/// Why use a Field AND a Property where you could just use Example 2?
private int age;
public int Age { get { return age; } }
private void setAge()
{
age = 1;
}
/// Example 2
/// Tidier code and better understanding of how Age2 can be accessed.
/// Personally I prefer this method, though am I right to use it over Example 1?
public int Age2 { get; private set; }
private void setAge2()
{
Age2 = 1;
}
}
【问题讨论】:
-
这些重复项均无效。他不是在问他是否应该使用字段与属性,而是在询问手动实现的属性与自动实现的属性。
-
@OP 还注意到自动实现的属性是在 C# 3.0 中引入的,但属性自 C# 1.0 起就在该语言中。手动定义属性的许多示例要么是遗留下来的旧代码示例,要么来自尚未(或尚未)习惯新语法的人。当然,在某些情况下,您可以手动执行自动道具无法执行的操作,但您发布的示例并非如此。
-
这可能是我最挣扎的地方,什么是新的,什么是更好的做法?如果示例 2 在早期的 .NET 版本中是不可能的,并且示例 1 是实现相同效果所必需的。令人欣慰的是,通过使用示例 2,我使用了更现代的语法,而不是在示例 1 中不必要地使我的代码臃肿。:)
标签: c# properties get set field