[C#多继承,使用受保护的成员

问题描述 投票:1回答:2

我使用继承几乎没有问题。受保护时,我既不能更改C类中first和second的值,也不能更改B类中first的值。如果这些变量是公共变量,那么一切正常,但是在这种情况下,使用protected有什么意义?

class A
{
    protected int first { get; set; }
}

class B : A
{
    protected int second { get; set; }

    public Show() 
    {
        A a = new A();
        a.first = 5;
    }
}

class C : B
{
    private int third { get; set; }

    static void Main()
    {
        B b = new B();
        b.first = 1;
        b.second = 2;
    }
}
c# multiple-inheritance protected
2个回答
3
投票

主要问题仅是由于将程序的入口点放在要测试的类中而引起的。因为Main()是静态的,所以您无法访问C的(继承的)实例成员。

因此分开:

class Program
{
    static void Main()
    {
        C c = new C();
        c.Test();
    }
}

您的类C继承自B,因此C可以像这样访问B的受保护成员:

class C : B
{
    private int third { get; set; }

    public void Test()
    {
        first = 1; // from A
        second = 2; // from B
        third = 3; // from C
    }
}

通过new内的BCB的实例之间没有关系,因此您可以访问的只有CBpublic成员。


1
投票

当您处理自己的类的实例时,您可以访问受保护的成员:

internal

如果允许您在基类的any实例上任意访问基类的class B :A { protected int second { get; set; } public show() { this.first = 5; //This is valid } } 成员,则将允许此操作:

protected

这对class DDefinitelyNotB : A { } class B :A { protected int second { get; set; } public show() { A a = new DDefinitelyNotB (); a.first = 5; } } 可能是不好的,它不希望刚从DDefinitelyNotB派生的other类能够干扰它从A继承的protected成员。

© www.soinside.com 2019 - 2024. All rights reserved.