gpt4 book ai didi

c# - 类属性,在内部可获取和可设置,但只能在外部获取

转载 作者:太空狗 更新时间:2023-10-29 20:45:34 24 4
gpt4 key购买 nike

我意识到这可能是非常基本的东西,但我不确定实现以下目标的最佳实践。

我有以下带有字符串属性 myString 的类:

public class MyClass
{
public string myString
{
get {
return myString;
}
}

public void AFunction()
{
// Set the string within a function
this.myString = "New Value"; // Error because the property is read-only
}
}

我希望 myString 属性满足以下条件:

  • 可在内部设置
  • 可在内部获取
  • 不可外部设置
  • 可从外部获取

所以我希望能够在类中设置变量 myString 并在类外部将其值设置为只读。

有没有一种方法可以在不使用单独的 get 和 set 函数并将 myString 属性设为私有(private)的情况下实现这一点,如下所示:

public class MyClass
{
private string myString { get; set; }

public void SetString()
{
// Set string from within the class
this.myString = "New Value";
}

public string GetString()
{
// Return the string
return this.myString;
}
}

上面的示例允许我在内部设置变量,但不能从类外部对实际属性 myString 进行只读访问。

我试过 protected 但这并不能使值从外部访问。

最佳答案

听起来你只是想要:

public string MyString { get; private set; }

这是一个具有公共(public) getter 和私有(private) setter 的属性。

根本不需要额外的方法。

(请注意,鉴于关键字 internal 在 C# 中的特定含义,此处使用“内部”一词可能会造成混淆。)

关于c# - 类属性,在内部可获取和可设置,但只能在外部获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15924108/

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