简体   繁体   中英

Cannot Access Protected Function in Derived Class in C#?

How to use protected function of base class in derived class?

public class A
{
  protected void Test()
  {
      // some code....
  }
}

public class B : A
{
  public void Test2()
  {
    A obj = new A();
    obj.Test(); // error thrown;
  }
}

When i tried to use the Test function of base class. It is throwing error..

You can call the Test() method directly without having to create a new object of the base type:

public class A
{
  protected void Test()
  {
      // some code....
  }
}

public class B : A
{
  public void Test2()
  {
    Test();  // Calls the test method in the base implementation of the CURRENT B object
  }
}

I think one could do it through a protected static method in the base class, without losing the encapsulation.

public class A
{
  protected void Test() { /* ... */ }

  protected static void Test(A obj)
  {
    obj.Test();
  }
}

public class B : A
{
  public void Test2()
  {
    A obj = new A();
    A.Test(obj);
  }
}

Effectively A.Test() can be called only from derived classes and their siblings.

A snippet for testing: http://volatileread.com/utilitylibrary/snippetcompiler?id=37293

That's because 'A's Test() is protected, which means, B sees it as private .

The fact that B inherits from A , and that A contains Test which is protected, doesn't mean that other objects can access Test , even though they inherit from that class.

Although:

Since B inherits from A , B contains the private method Test() . so, B can access it's own Test function, but that doesn't mean B can access A s Test function.

So:

public class A
{
  protected void Test()
  {
      // some code....
  }
}

public class B : A
{
  public void Test2()
  {
    this.Test(); // Will work!
  }
}

Test is protected within an instance of object A.

Just call

this.Test()

No need to create the object A within B.

Seems you misunderstood the word "protected". Have a look at msdn: http://msdn.microsoft.com/en-us/library/bcd5672a(v=vs.71).aspx

Your example needs to be like this:

public class A
{
  protected void Test()
  {
      // some code....
  }
}

public class B : A
{
  public void Test2()
  {
    this.Test();
  }
}

Protected methods are only available to derived types. In other words you are trying to access the method publicly when you create an instance of A.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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