C#中的继承问题. [英] Problem with inheritance in C#.
问题描述
我对C#继承有一点问题.很简单,但我想不起来!
假设我有一个父类和一个子类(child:parent).
我只想知道是否定义(子代=新父代)可以访问子代属性?因为我尝试过,但是我做不到,顺便说一句,我认为它应该可以工作..
这是一个示例代码:
I have a little problem with C# inheritance. It''s easy but I cant figure it out!
Suppose I have a parent class and a child class(child:parent).
I just want to know if we define (child = new parent) can we access to child properties? Because I tried it but I couldn''t do that, by the way i think it should work..
Here is a example code:
public class Parent
{
private int _Parent1;
public int Parent1
{
get { return _Parent1; }
set { _Parent1 = value; }
}
}
public class Child1 : Parent
{
private int _Child1Prop;
public int Child1Prop
{
get { return _Child1Prop; }
set { _Child1Prop = value; }
}
}
假设
suppose
Parent test = new Child1();
这可能吗?
Is this possible:?
test.Child1Prop = some value;
推荐答案
您无法编写
You cannot write
Child=new Parent;
编译器会 d抱怨.
The compiler would complain.
好的,您现在改写了这个问题:
OK, you rephrased the question, now:
Parent test = new Child1();
test.Child1Prop = some value;
不可能是不可能的.
但是,例如:
is not possible.
However, for instance:
Parent parent = new Child1();
(parent as Child1).Child1Prop = 5;
会很好.
[/update]
would work fine.
[/update]
这不可能:
This isn''t possible:
child1 test = new Parent;
您不能将基础强制转换为子对象.根据我的经验,这是不可能的.您可以像这样在Child1类中实现构造函数:
You can''t cast base to the child object. From my experience this isn''t possible. You can implement constructor in Child1 class like this:
public Child1(Parent parent)
{
_Child1Prop = 2;
}
但是您可以执行以下操作:
BUT you can do something like this:
public class Parent
{
}
public class Child1 : Parent
{
}
public class Child2 : Child1
{
}
public class Child3 : Child2
{
}
//-------------- somewhere in Main -------
Child3 ch3 = new Child3();
Child1 ch1 = (Child1)ch3;
Child2 ch2 = (Child2)ch1;
希望您能这样问.
I hope you''re asked this.
child1 test = new Parent;
根本不可能.
您的解决方案有效,但我不想使用转换!!"
不管有没有强制转换,都无法做这样的事情.
您可以执行以下操作:
simply this isn''t possible.
"your solution works but i dont want to use casting!!!"
There is no way to do something like that with or without casting, it''s not allowed.
You can do this:
public class Child1 : Parent
{
public static implicit operator Child2(Child1 ch2)
{
return new Child2();
}
}
public class Child2 : Child1
{
Child2 ch2 = new Child1();
}
但在这种情况下不是:
but not in this case:
child1 test = new Parent;
这篇关于C#中的继承问题.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!