Let take a test example:
class A
{
public A()
{
this.Test(); //I want to call Test exactrly from class A!!! here
}
public virtual void Test ()
{
Console.WriteLine("I am A!");
}
}
class B : A
{
public B() { }
public override void Test()
{
开发者_JS百科 Console.WriteLine("I am B!");
}
}
//Somewhere in code
B b = new B(); //I want It displays "I am A" instead of "I am B"
Is there a way to do so? P.S.: I know It is a bad design but I want to know in order to improve my knowledge of C#.
No - you can't call a virtual method in a non-virtual way. (Not from C# directly, anyway... you can in IL, but you can't express that in C#.)
In this case, if the code wishing to make the call is in A, then you can just make a non-virtual method containing the behaviour you're interested in, and then potentially call that non-virtual method from the virtual method too.
The point of having and overidable metheod is that you can transparently replace functionality and expect the class to function reasonably. What you're asking for is a base class to have knowledge about classes which may derive from this... thats not the principle of OO design.
If you want to call a method which hasn't been overridden.. don't make the method overidable.
You can't if you override the virtual method. But you can do that if you hide it with new instead (even if I wouldn't do that, but you already know that this is bad design :-)).
I mean that if you define your Test method in class B like this:
public new void Test()
{
Console.WriteLine("I am B!");
}
and then execute it declaring the variable you assign the instance of B as being of type A, you obtain what you want:
A b = new B();
b.Test();
If you want to execute the B version of the method you just have to declare tha variabla as A:
B b = new B();
b.Test();
精彩评论