C#自动属性 [英] C# automatic property

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

问题描述

请问的C#3.0的自动属性完全取代提起?



我的意思是,我可以直接使用属性,而不是提起财产作为私有支持字段。 (对不起,我明白像只)

  int类型的; 

公众诠释一个
{
获得;设置;
}


解决方案

当你访问属性代码 - 无论是内部还是外部类 - 它总是作为一个属性进行访问。在大多数情况下,这并不重要 - 但它的确实的意思是,你不能引用,你就可以做,如果它是一个场传递



只有的一段代码,直接访问支持字段(反射除外)是财产本身。



据是一个属性,纯粹而简单。它不能作为一个领域 - 这是作为一个属性。 C#编译器的的替代访问它与现场访问。访问它总是属性访问。这可能深受当然的 JIT 的编译器内联,但是这没什么特别的。至于CLR而言这只是一个正常的属性(它恰好有适用于它的 [编译器生成] 属性)。



但是,为了回答你原来的问题 - 是的,自动属性意味着你不需要自己声明支持字段。实际上,这样的:

 公众诠释美孚{搞定;组; } 



被翻译成

 私人诠释<>富; //或者其他一些难以启齿的名字
公众诠释美孚
{
获得{返回<>富; }
组{<>美孚=价值; }
}

您的无法的直接访问所产生的场C#代码,因为它有一种说不出名字。你会看到,如果你审视与反思的类型,虽然它的存在 - 在CLR不一个自动实现的属性和一个正常


区分

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;
 }

解决方案

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.

这篇关于C#自动属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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