gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:27:30 24 4
gpt4 key购买 nike

考虑类:

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 usedas though they are public data members, but they are actually specialmethods called accessors. This enables data to be accessed easily

和:

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

A get property accessor is used to return the property value, and aset accessor is used to assign a new value. These accessors can havedifferent access levels. For more information, see AccessorAccessibility.

The value keyword is used to define the value being assigned by theset 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com