C# .NET 1.1 - MethodBase.Invoke on virtual methods (dynamic method lookup)
-
Hello all, I was wondering if there was a way to overcome the "dynamic method lookup" done by MethodBase.Invoke when invoking virtual methods. For example:
public class A
{
public virtual int Call()
{
return 1;
}
}public class B : A
{
public override int Call()
{
return 2;
}
}... invoking it somewhere else ...
B obj = new B();
MethodInfo method = typeof(A).GetMethod("Call", BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public);
int a = method.Invoke(this, null);the final value of
a
would be 2 and not 1. Anyone know how to get around this? (P.S. A page on the columbia university website details the default behavior[^] under the 'Remarks' section of Invoke ) Thanks in advance!r -€
-
Hello all, I was wondering if there was a way to overcome the "dynamic method lookup" done by MethodBase.Invoke when invoking virtual methods. For example:
public class A
{
public virtual int Call()
{
return 1;
}
}public class B : A
{
public override int Call()
{
return 2;
}
}... invoking it somewhere else ...
B obj = new B();
MethodInfo method = typeof(A).GetMethod("Call", BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public);
int a = method.Invoke(this, null);the final value of
a
would be 2 and not 1. Anyone know how to get around this? (P.S. A page on the columbia university website details the default behavior[^] under the 'Remarks' section of Invoke ) Thanks in advance!r -€
That's how virtual methods work, even if you call them directly.
obj.Call
would return 2, not 1, so why shouldMethod.Invoke
work differently? It would amount to bypassing the virtual method mechanism, wouldn't it?Regards Senthil [MVP - Visual C#] _____________________________ My Blog | My Articles | My Flickr | WinMacro
-
That's how virtual methods work, even if you call them directly.
obj.Call
would return 2, not 1, so why shouldMethod.Invoke
work differently? It would amount to bypassing the virtual method mechanism, wouldn't it?Regards Senthil [MVP - Visual C#] _____________________________ My Blog | My Articles | My Flickr | WinMacro
Yes, that makes sense. But somehow, inside the method, doing something like
base.Call()
will actually invoke the superclass method. Is there any way to simulate that functionality outside of the overriden method call?
r -€
-
Yes, that makes sense. But somehow, inside the method, doing something like
base.Call()
will actually invoke the superclass method. Is there any way to simulate that functionality outside of the overriden method call?
r -€
Yeah it is possible ... instead of overriding the function in the derived class use the key word new ..ie class B : A { public void new Call() { return 2; } } Now if u create a object of class A and call the Call() function it would call A's definition of Call and not B's Hope it helps