我在某个地方读到,拥有公共财产比在一个班级中拥有公共成员更可取.
这只是因为抽象和模块化吗?还有其他任何超越原因吗?
属性访问由编译器转换为函数调用.对于没有备份存储的属性(例如public string UserName { get; set; }),与直接成员访问相比,性能开销会是多少?(我知道它通常不会有所作为,但在我的一些代码中,属性被访问了数百万次.)
Edit1:我在整数成员和属性上运行了一些测试代码,公共成员的速度是属性的3-4倍.(在调试中~57 ms.vs~206 ms.在Release中57与97 vs. 97是最常见的运行值).对于1000万次读写,两者都足够小,不足以证明改变任何东西.
码:
class TestTime1
{
public TestTime1() { }
public int id=0;
}
class TestTime2
{
public TestTime2() { }
[DefaultValue(0)]
public int ID { get; set; }
}
class Program
{
static void Main(string[] args)
{
try
{
TestTime1 time1 = new TestTime1();
TestTime2 time2 = new TestTime2();
Stopwatch watch1 = new Stopwatch();
Stopwatch watch2 = new Stopwatch();
watch2.Start();
for (int i = 0; …Run Code Online (Sandbox Code Playgroud)