简体   繁体   English

使用父方法派生类

[英]Derived Class using Parent Method

Why can't i access the age method from either class A or B? 为什么我不能从A级或B级访问年龄方法? I thought because it's a protected method, derived class instances should be able to use it? 我以为因为它是受保护的方法,派生类实例应该能够使用它吗?

class Program
{
    public static void Main(string[] args)
    {



    }

    public static void Test(A test)
    {
        A a = new A();
        B b = new B();

        Console.WriteLine(a.Age());
        Console.WriteLine(b.Age());
    }
}

public class A
{
    public virtual string Name { get { return "TestA"; } }
    protected string Age() { return "25";}
}

public class B : A
{

    public override string Name { get { return "TestB"; }  }
    public string Address { get; set; }
}

---As suggested by Jon Skeet-- ---正如Jon Skeet所说 -

 public class B : A
 {

    public override string Name { get { return "TestB"; }  }
    public string Address { get; set; }

    public void Testing()
    {
        B a = new B();
        a.Age();
    }
}

Protected means it can be used from code in the derived classes - it doesn't mean it can be used "from the outside" when working with derived classes. 受保护意味着它可以从派生类中的代码中使用 - 这并不意味着它可以在使用派生类时“从外部”使用。

The protected modifier can be somewhat tricky, because even a derived class can only access the protected member through instances of its own class (or further derived classes). protected修饰符可能有些棘手,因为即使派生类也只能通过其自己的类(或其他派生类)的实例访问受保护的成员。

So within the code of B, you could write: 所以在B的代码中,你可以写:

A a = new A();
Console.WriteLine(a.Age()); // Invalid - not an instance of B
B b = new B();
Console.WriteLine(b.Age()); // Valid - an instance of B
A ba = b;
Console.WriteLine(ba.Age()); // Invalid

The last of these is invalid because even though at execution time it's accessing the member on an instance of B , the compiler only knows of ba as being of type A . 最后一个是无效的,因为即使在执行时它正在访问B实例上的成员,编译器也只知道baA类型。

Here's the start of section 3.5.3 of the C# 5 specification, which may clarify things: 这是C#5规范3.5.3节的开头,它可以澄清一些事情:

When a protected instance member is accessed outside the program text of the class in which it is declared, and when a protected internal instance member is accessed outside the program text of the program in which it is declared, the access must take place within a class declaration that derives from the class in which it is declared. 当在声明它的类的程序文本之外访问protected实例成员时,并且当在声明它的程序的程序文本之外访问protected internal实例成员时,访问必须在类中进行声明派生自声明它的类。 Furthermore, the access is required to take place through an instance of that derived class type or a class type constructed from it. 此外,需要通过该派生类类型的实例或从其构造的类类型进行访问。 This restriction prevents one derived class from accessing protected members of other derived classes, even when the members are inherited from the same base class. 此限制可防止一个派生类访问其他派生类的protected成员,即使这些成员是从同一基类继承的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM