Class属性,Gettable和内部可设置,但只能在外部获取

Luk*_*uke 6 c# properties class

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

我有以下类与字符串属性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
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望以下内容适用于该myString物业:

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

所以我希望能够myString在类中设置变量,并使其值从类外部读取.

有没有办法实现这一点,而无需使用单独的get和set函数并使myString属性私有,如下所示:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

我尝试过,protected但这并不能使价值从外部进入.

Jon*_*eet 11

听起来你只是想要:

public string MyString { get; private set; }
Run Code Online (Sandbox Code Playgroud)

这是一个有公共吸气者和私人二传手的财产.

根本不需要额外的方法.

(请注意,考虑到internalC#中关键字的具体含义,使用"内部"一词可能会造成混淆.)


bea*_*dev 9

您只能为类成员允许setter,通常是构造函数:

public class MyClass
{
    public string myString { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)

或者你可以在内部/汇编程序中允许setter:

public class MyClass
{
    public string myString { get; internal set; }
}
Run Code Online (Sandbox Code Playgroud)

吸气剂将公开.