简体   繁体   中英

How Can a private member Accessable in Derived Class in C#?

如何在C#中将BaseClass私有函数访问到DerivedClass?

Either:

  1. Elevate its access from private to protected
  2. or, add another protected member that accesses it, and use this instead from the derived class
  3. or, use reflection
  4. or, change the code so you don't need to access it

Of the 4, I would chose 1 if it's a private property or method, and 2 if it's a private field. I would add a protected property around the field.

It can't. That's the whole purpose of the private access modifier :

The type or member can be accessed only by code in the same class or struct.

Of course you could always use reflection.

This answer is for completeness only. In almost all cases, use the suggestions in the other answers.

The other answers are all correct, except there's one situation in which a derived class can access a private member in the base class: when the derived class is a nested type of the base class. This can actually be a useful feature for mimicking Java enums in C#. Sample code (not of Java enums, just the "accessing a private member" bit.)

public class Parent
{
    private void PrivateMethod()
    {
    }

    class Child : Parent
    {
        public void Foo()
        {
            PrivateMethod();
        }
    }
}

With reflection:

FieldInfo f = typeof(Foo).GetField("someField", BindingFlags.Instance | BindingFlags.NonPublic);
fd.SetValue(obj, "New value");

It can't. If you want the method to be accessible to derived classes then you need to make it protected instead.

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