[英]Multi level inheritance in c#
I am trying to call a method from class A and apply it to a value in class C: 我试图从类A调用一个方法并将其应用于类C中的值:
class A
{
//my code here
public virtual string calculatebnft()
{
string bnft = "";
//my code here
return bnft;
}
}
class B : A
{
//my code here
public override string calculatebnft()
{
string bnft = "";
//my code here
return bnft;
}
}
class C : B
{
//my code here
}
In my Main method: 在我的Main方法中:
C c1=new C();
//my code here
string bnft=c1.calculatebnft();
MessageBox.Show(bnft);
When I run program it always runs class B's method calculatebnft(). 当我运行程序时,它总是运行B类的方法calculatebnft()。 How can I call calculatebnft() from A instead?
如何从A调用calculatebnft()呢? The rest of code from B "which is working correctly".
其余代码来自B“正常工作”。
You can't do that without changing B
code. 如果不改变
B
代码就不能这样做。 You have to change calculatebnft
method from override
to new
: 您必须将
calculatebnft
方法从override
更改为new
:
class B : A
{
//my code here
public new string calculatebnft()
{
string bnft = "";
//my code here
return bnft;
}
}
with that you could do following: 你可以这样做:
string bngt = ((A)c1).calculatebnft();
From the outside there is no way to call a base class instance of a virtual method. 从外部无法调用虚方法的基类实例。 It is simply not possible because it is forbidden by the CLR (possible, but not verifiable).
这是不可能的,因为它被CLR禁止(可能,但不可验证)。 The only way to get access to it is for
A
or B
to give you another method on which to call the functionality. 访问它的唯一方法是
A
或B
为您提供另一种方法来调用该功能。 For example 例如
class A {
public string callMe() {
return ...;
}
public virtual string calculatebnft() {
return callMe();
}
}
Now a caller who wants the A
version of calculatebnft
can use callMe
instead. 现在需要
A
版本的calculatebnft
的调用者可以使用callMe
。
In general though I'd consider this bad practice. 总的来说,虽然我认为这是一种不好的做法。 If there is a situation where you really wanted the base class version of a virtual method then it's probably not the best method to be virtual.
如果您确实需要虚拟方法的基类版本,那么它可能不是虚拟的最佳方法。
I don't think that's possible this way. 我认为这不可能。
But for example you can do something like this: 但是,例如你可以做这样的事情:
class A
{
//my code here
public virtual string calculatebnft()
{
string bnft = "A";
//my code here
return bnft;
}
}
class B : A
{
public string calculatebnftFromA()
{
return base.calculatebnft();
}
//my code here
public override string calculatebnft()
{
string bnft = "B";
//my code here
return bnft;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.