继承:不包含的定义,也没有扩展方法接受第一个参数 [英] Inheritance : does not contain a definition for and no extension method accepting a first argument
问题描述
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屋!