gpt4 book ai didi

c# - 是否可以在该属性的 getter 中获取属性值?

转载 作者:太空宇宙 更新时间:2023-11-03 21:28:53 24 4
gpt4 key购买 nike

我有一个具有以下属性的基本测试控制台应用程序:

public static string testString { get{ } set{ } }

我想对属性进行某种单例设置,如果属性值为 null,我将初始化属性并返回属性值。如果它不为空,我将返回当前属性值。

撇开不好的做法不谈,这是否可能不使用额外的变量?

尝试使用传统方法检查 get{} 中的属性值当然会产生 stackoverflow 异常。我假设每次它尝试检查 null 时,它只是再次使用 getter 并陷入无限循环。

最佳答案

Properties只是 getter/setter 方法的语法糖。因此它们背后没有内置存储。

Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.

因此您必须创建一个字段左右。

(还有 auto-implemented properties ,编译器会自动为其创建支持者字段。但无论如何您都无法直接访问这些字段。)

关于c# - 是否可以在该属性的 getter 中获取属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25299413/

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