是C#性能其实方法? [英] Are C# properties actually Methods?

查看:237
本文介绍了是C#性能其实方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

直到现在,我下的IM pression的属性&放大器; 方法在C#中两个不同的东西。但是,我不喜欢的东西如下:

Till now, I was under the impression that Properties & Methods are two different things in C#. But then I did something like below.

这是一个大开眼界给我。我期待一个属性 stringProp 和一个方法 stringProp 而是我得到了这一点。

and this was an "Eye Opener" to me. I was expecting one property stringProp and one method stringProp but instead I got this.

为什么发生这种情况?有人可以解释一下吧。

Why this happened? can someone explain please.

推荐答案

是的,编译器会生成一对get和set方法的属性,以及一个私人支持字段的自动实现的属性。

Yes, the compiler generates a pair of get and set methods for a property, plus a private backing field for an auto-implemented property.

public int Age {get; set;}

变成等价的:

becomes the equivalent of:

private int <Age>k__BackingField;

public int get_Age()
{
     return <Age>k__BackingField;
}

public void set_Age(int age)
{
    <Age>k__BackingField = age;
}

code访问你的财产将被编译调用这两个方法之一。这也正是为什么改变公共领域是公共财产是一个重大更改的原因之一。

Code that accesses your property will be compiled to call one of these two methods. This is exactly one of the reasons why changing a public field to be a public property is a breaking change.

请参阅乔恩斯基特的为什么属性物质

这篇关于是C#性能其实方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆