C# 是否可以在基类中从派生类设置私有setter而不使用公共setter?

C# 是否可以在基类中从派生类设置私有setter而不使用公共setter?,c#,getter-setter,C#,Getter Setter,是否可以向基类setter提供私有访问权限,并且只能从继承类使用它,就像受保护的关键字工作一样 public class MyDerivedClass : MyBaseClass { public MyDerivedClass() { // Want to allow MyProperty to be set from this class but not // set publically public MyProperty =

是否可以向基类setter提供私有访问权限,并且只能从继承类使用它,就像受保护的关键字工作一样

public class MyDerivedClass : MyBaseClass
{
    public MyDerivedClass()
    {
        // Want to allow MyProperty to be set from this class but not
        // set publically
        public MyProperty = "abc";
    }
}

public class MyBaseClass
{
    public string MyProperty { get; private set; }
}

为什么不使用受保护的

public string MyProperty { get; protected set; }

受保护的成员可以在其类内以及由派生类实例访问


使用而不是专用。您只需将setter设置为:


另请参见

保护是正确的方法,但为了便于讨论,可以这样设置私有财产:

public class MyDerivedClass : MyBaseClass
{
    public MyDerivedClass() : base(myProperty: "abc") { }
}

public class MyBaseClass
{
    public string MyProperty { get; private set; }

    public MyBaseClass(string myProperty) { 
        this.MyProperty = myProperty;
    }
}

“公共字符串MyProperty{get;protected set;}”有什么问题?:您描述的是“protected”修饰符,然后说“protected修饰符的工作方式相同”。您提到了
protected
关键字。。。你为什么不使用它?@DrewR-道歉-打字道歉,我不知道你可以在属性上设置受保护的关键字!
public class MyDerivedClass : MyBaseClass
{
    public MyDerivedClass() : base(myProperty: "abc") { }
}

public class MyBaseClass
{
    public string MyProperty { get; private set; }

    public MyBaseClass(string myProperty) { 
        this.MyProperty = myProperty;
    }
}