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

3
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' 的内容,也没有接受类型为 'Example.Parent' 的第一个参数的扩展方法 'AttrChild'。”
有人可以解释一下这是为什么吗?

“当我运行这个程序”是什么意思?它是否能编译通过? - Mark Seemann
AttrChild改为公共的,像这样:public AttrChild { get; set; }。并将变量p的类型更改为Child - Yacoub Massad
3
你可能正在创建一个 Child 的实例,但是你的变量 p 只看到了 Parent 中已经存在的部分(因为你将其类型定义为 Parent)......并且在 Parent 类中没有 AttrChild - marc_s
不,它不会。当我按F5键时。 - user
1
此外,Child 中没有无参构造函数。您能解释一下您想要做什么吗? - Yacoub Massad
2个回答

2

当你将Child实例分配给类型为Parent的变量时,你只能访问在Parent中声明的成员。

你必须向下转换回Child才能访问Child独有的成员:

Parent p = new Child();

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

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


0

一个parent实例只能访问parent类中可用的方法,如果您想要访问child方法,则需要创建一个child类。问题在于您正在尝试从parent类中访问child方法。

使用继承,如果您希望调用child类中的方法,则需要创建一个新的child类实例。这样做的目的是使一个parent可以有多个继承自它的child类,如果您的示例代码有效,则当一个parent有多个child类时会导致问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接