本文介绍了C#中私有成员的继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在c#中继承类时,私有成员是否被继承?我已经读过一些与此相关的主题,有人告诉私有成员是继承的,但不能访问私有成员,有人告诉我在继承类时它不是继承的.请解释一下这个概念.如果是继承的,任何机构都可以给出解释吗?

Are private members inherited when inheriting the class in c#?I have read some topic related to this, somebody telling that private members are inherited but cannot access the private members, somebody telling that it is not inherited when inheriting the class. Please explain the concept. if it is inheriting can any body give an explanation?

谢谢

推荐答案

如果我正确理解了您的问题,那么您就不必担心可访问性,而只需担心私有成员是

If I understand your question correctly then you're not concerned about the accessibility you are only concerned about private members are inherited or not

答案是肯定的,所有私有成员都是继承的,但您不能在没有反思的情况下访问它们.

Answer is yes, all private members are inherited but you cant access them without reflection.

public class Base
{
    private int value = 5;

    public int GetValue()
    {
        return value;
    }
}

public class Inherited : Base
{
    public void PrintValue()
    {
        Console.WriteLine(GetValue());
    }
}

static void Main()
{
    new Inherited().PrintValue();//prints 5
}

这篇关于C#中私有成员的继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 08:03