加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#属性是隐藏实例变量还是更深入的事情?

发布时间:2020-12-16 00:03:59 所属栏目:百科 来源:网络整理
导读:考虑班级: public class foo{ public object newObject { get { return new object(); } }} 根据MSDN: Properties are members that provide a flexible mechanism to read, write,or compute the values of private fields. Properties can be used as th
考虑班级:

public class foo
{
    public object newObject
    {
        get
        {
            return new object();
        }
    }
}

根据MSDN:

Properties are members that provide a flexible mechanism to read,
write,or compute the values of private fields. Properties can be used
as though they are public data members,but they are actually special
methods called accessors. This enables data to be accessed easily

和:

Properties enable a class to expose a public way of getting and
setting values,while hiding implementation or verification code.

A get property accessor is used to return the property value,and a
set accessor is used to assign a new value. These accessors can have
different access levels. For more information,see Accessor
Accessibility.

The value keyword is used to define the value being assigned by the
set indexer.

Properties that do not implement a set method are read only.
while still providing the safety and flexibility of methods.

这是否意味着在某个时间点newObject属性的值具有对返回的新对象的引用?

编辑从属性中删除readonly

edit2也想澄清一点,这不是一个财产的最佳用途,但它试图更有效地说明问题.

解决方法

您在每次访问属性时返回一个新对象,这不是属性的预期行为.相反,您应该每次返回相同的值(例如,存储在字段中的值).属性getter只是一种返回值的方法的美化语法.你的代码编译成这样的东西(编译器通过在属性名前加上get_来创建一个getter,然后将其作为IL发出):

public class foo
{
    public object get_newObject()
    {
        return new object();
    }
}

每次调用getter都会创建一个foo不知道或无法访问的新对象.

Does this therefore mean that at some point in time the value of the newObject property has a reference to the returned new object?

没有.

使用支持字段的属性:

class Foo {

  readonly Object bar = new Object();

  public Object Bar { get { return this.bar; } }

}

使用自动属性:

class Foo {

  public Foo() {
    Bar = new Object();
  }

  public Object Bar { get; private set; }

}

使用与公共字段相同的简单语法访问属性.但是,通过使用属性,您可以向getter和setter添加代码,允许您执行getter中的延迟加载或setter中的验证(以及更多)等内容.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读