将私有成员封装为属性与在没有私有成员的情况下定义属性有什么区别? [英] What's the difference between encapsulating a private member as a property and defining a property without a private member?
问题描述
封装这样的私有成员之间有什么区别(性能,内存等)
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
并定义这样的属性
public int Age
{
get ;
set ;
}
C#编译器为自动实现的属性 几乎与您的第一个示例相同(它使用私有的后备字段),因此我不必为此太担心. /p>
仅 的真正区别在于,它使用 [CompilerGenerated]
属性.这不会对获取和设置属性的性能产生任何影响. (作为次要的nitpick,应该稍微增加一下程序集二进制文件的大小).
除了简洁之外,我喜欢自动实现的属性的地方在于,它甚至阻止了声明类型访问后备字段而不是属性(后备字段是匿名的).这使代码更加清晰,并且通常也使重构/更改属性实现更加容易.
What's the difference (Performance, memory...etc) between encapsulating a private member like this
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
and define a property like this
public int Age
{
get ;
set ;
}
The code that the C# compiler generates for auto-implemented properties is almost identical to your first example (it uses a private, backing field), so I wouldn't worry about it too much.
The only real difference is that it decorates the property getter and setter with the [CompilerGenerated]
attribute. This shouldn't have any impact on the performance of getting and setting the property. (As a minor nitpick, that should increase the size of the assembly's binary ever so slightly).
What I like about auto-implemented properties, other than brevity of course, is that it prevents even the declaring type from accessing the backing-field instead of the property (the backing-field is anonymous). This brings clarity to the code, and generally makes refactoring / changing the property implementation easier too.
这篇关于将私有成员封装为属性与在没有私有成员的情况下定义属性有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!