将私有成员封装为属性与定义没有私有成员的属性有什么区别? [英] What's the difference between encapsulating a private member as a property and defining a property without a private member?
问题描述
像这样封装私有成员有什么区别(性能、内存...等)
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; }
}
并定义这样的属性
public int Age
{
get ;
set ;
}
推荐答案
C# 编译器为 自动实现的属性几乎与您的第一个示例相同(它使用私有的支持字段),所以我不会太担心.
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.
唯一真正的区别在于它使用 [CompilerGenerated]
属性.这不应该对获取和设置属性的性能产生任何影响.(作为一个小小的挑剔,这应该会稍微增加程序集二进制文件的大小).
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屋!