gpt4 book ai didi

c# - 带有 set & get 的显式只读属性是否等同于 get & private set?

转载 作者:行者123 更新时间:2023-11-30 14:00:11 25 4
gpt4 key购买 nike

假设我有 2 个属性

public readonly list<int> numberListReadonly { get; set; }

public list<int> numberListPrivateSet { get; private set; }

对于那些属性,我可以在 Foo 中有一个构造函数/私有(private)函数,我可以在没有错误的情况下启动这些列表

public Foo()
{
numberListReadonly = new list<int>();
numberListPrivateSet = new list<int>();
}

public void FooInside()
{
numberListReadonly = new list<int>();
numberListPrivateSet = new list<int>();
}

当我从课外访问时

void FooOutside()
{
Foo.numberListReadonly = new List<int>();
Foo.numberListPrivateSet = new List<int>()
}

编译器抛出错误,这是预期的。
“Foo.numberListReadonly 不能分配给——它是只读的”
“无法将 Foo.numberListPrivateSet 分配给 -- 它是只读的”


我搜索了一下,似乎“常见做法”是在“只读”属性上使用私有(private)集,并具有类内“设置”的能力
那么带有set & get的显式只读属性是否等同于get & private set?

最佳答案

没有。

私有(private)集意味着您可以在类中的任何位置更改成员的值。 Readonly with set 意味着它只能在构造函数中设置,从而保证它不会在其他任何地方被更改。

关于c# - 带有 set & get 的显式只读属性是否等同于 get & private set?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11661583/

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