c# - C# 属性是否隐藏了实例变量或者是否有更深层次的原因?

标签 c# .net

考虑类:

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 属性的值引用了返回的新对象?

编辑 从属性中删除只读

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

}

使用与公共(public)字段相同的简单语法访问属性。但是,通过使用属性,您可以向 getter 和 setter 添加代码,从而允许您在 getter 中进行延迟加载或在 setter 中进行验证(等等)。

关于c# - C# 属性是否隐藏了实例变量或者是否有更深层次的原因?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10917437/

相关文章:

c# - ASP.NET 预编译期间出现类型解析错误

c# - 为什么 Assert.AreEqual 在 <Object, Object> 上失败?类型不匹配?

c# - 保存我的 DataGridView 的 "AllowUserToOrderColumns"的设置

c# - 区分大小写 Order by 2 个首字母

c# - .NET 及更高版本 : best practices for using double arithmetic

c# - EventArgs 作为事件模式中的基类的目的是什么?

c# - 拆箱后无法访问类(class)成员

c# - Xamarin.Forms webview 身份验证,导航到新页面(Shell)并需要再次重新身份验证?

c# - 关于T型的问题

c# - 从 DataGridView 到 Excel 2002 的神秘异常复制/粘贴