是否可以在派生类中设置基类设置中的私有setter而不公开?

时间:2013-08-15 10:10:03

标签: c# getter-setter

是否可以提供对基类设置器的私有访问权限,并且只能从继承类中获取它,与protected关键字的工作方式相同?

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; }
}

4 个答案:

答案 0 :(得分:16)

为什么不使用protected

public string MyProperty { get; protected set; }

protected (C# Reference)

  

受保护的成员可以在其类和派生类实例中访问。

答案 1 :(得分:3)

您只需将设置器设为protected,如:

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

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

另见Access Modifiers (C# Reference)

答案 2 :(得分:1)

使用protected代替私有。

答案 3 :(得分:0)

受保护是正确的方法,但为了讨论起见,可以通过这种方式设置私有财产:

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;
    }
}