I am trying to call a method from class A and apply it to a value in class 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:
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(). How can I call calculatebnft() from A instead? The rest of code from B "which is working correctly".
You can't do that without changing B
code. You have to change calculatebnft
method from override
to 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). The only way to get access to it is for A
or B
to give you another method on which to call the functionality. 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.
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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.