问题
Does the automatic property of C# 3.0 completely replace the filed?
I mean,I can directly use the property instead of filed as property serves as private backing field.(sorry,I understand like that only).
int a;
public int A
{
get;set;
}
回答1:
When you access the property from code - whether inside or outside the class - it is always accessed as a property. In most cases, this is unimportant - but it does mean that you can't pass it by reference, which you would be able to do if it were a field.
The only piece of code which accesses the backing field directly (reflection aside) is the property itself.
It is a property, pure and simple. It isn't available as a field - it's available as a property. The C# compiler doesn't replace accesses to it with field accesses. Accesses to it are always property accesses. It may well be inlined by the JIT compiler of course, but that's nothing special. As far as the CLR is concerned it's just a normal property (which happens to have the [CompilerGenerated]
attribute applied to it).
But to answer your original question - yes, the automatic property means you don't need to declare the backing field yourself. Effectively, this:
public int Foo { get; set; }
is translated into
private int <>Foo; // Or some other unspeakable name
public int Foo
{
get { return <>Foo; }
set { <>Foo = value; }
}
You cannot access the generated field directly in C# code, as it has an unspeakable name. You'll see it's present if you examine the type with reflection though - the CLR doesn't distinguish between an automatically implemented property and a "normal" one.
回答2:
Yes, the automatic property has its own holding field.
When you define an automatic property, the compiler will create the necessary backing field. It is not available as a field from regular code, but it is there and you can access it via reflection if you really need it.
Please see this guide for more info: http://msdn.microsoft.com/en-us/library/bb384054.aspx
回答3:
There is some compiler magic involved, such as with delegates, and so. You can see it as if the compiler takes charge of creating the necessary code that otherwise you would have to type in explicitly.
来源:https://stackoverflow.com/questions/1735235/c-sharp-automatic-property