继承:不包含接受第一个参数的定义,也不包含扩展方法

时间:2015-11-29 20:17:47

标签: c# inheritance

abstract class Parent
{
        protected string attrParent;

        public AttrParent { get; protected set }

        public Parent(string sParent)
        {
            AttrParent = sParent;
        }
}

class Child : Parent
{
        private string attrChild;

        public AttrChild { get; private set }

        public Child(string sParent, string sChild) : base(sParent)
        {
            AttrChild = sChild;
        }
}

class Program
{
        static void Main(string[] args)
        {
            Parent p = new Child();

            p.AttrChild = "hello";
        }
}

运行此程序时,出现以下错误:

  

'Example.Parent'不包含'AttrChild'的定义,也没有扩展方法'AttrChild'接受类型'Example.Parent'的第一个参数“

有人可以解释为什么会这样吗?

2 个答案:

答案 0 :(得分:2)

当您将Child个实例分配给键入Parent的变量时,您只能访问Parent上声明的成员。

您必须将其转发回Child才能访问Child - 仅限会员:

Parent p = new Child();

Child c = (Child)p;
c.AttrChild = "hello";

该转换可能在运行时失败,因为可能有一个不同的类继承Parent

答案 1 :(得分:0)

parent实例只能访问parent类中可用的方法。如果要访问创建child类所需的child方法。如果您尝试从child类访问parent方法,则会出现问题。

如果您希望调用child类中的方法,则需要继承,您需要创建child类的新实例。 parent可以包含多个child类的目的,如果您的示例中的代码有效,那么当parent有多个child类时会导致问题

相关问题