继承:不包含的定义,也没有扩展方法接受第一个参数 [英] Inheritance : does not contain a definition for and no extension method accepting a first argument

查看:90
本文介绍了继承:不包含的定义,也没有扩展方法接受第一个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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";
        }
}

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

When I run this program, I get the following error :

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

'Example.Parent' does not contain a definition for 'AttrChild' and no extension method 'AttrChild' accepting a first argument of type 'Example.Parent'"

有人可以解释为什么吗?

Can anybody explain why this is?

推荐答案

Child实例分配给类型为Parent的变量时,您只能访问在Parent上声明的成员.

The moment you assign Child instance to variable typed as Parent you can only access members declared on Parent.

您必须将其向下转换回Child才能访问仅Child个成员:

You'd have to downcast it back to Child to access Child-only members:

Parent p = new Child();

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

该强制转换可能会在运行时失败,因为可能存在继承Parent的其他类.

That cast might fail at runtime, because there might be a different class that inherits Parent.

这篇关于继承:不包含的定义,也没有扩展方法接受第一个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆