"Allan Ebdrup" <(E-Mail Removed)> wrote:
> I'm writing some code where I have have a class that implements 4 methods
> (class A)
> I only want to call these methods from the base class if they have been
> overridden in a sub class (Class B) I guess I could have some properties
> that specify wether to call the methods, but I would like to call them
> automatically when they are overridden, how do I do this using reflection?
The check for whether or not they have been overridden will be
relatively expensive. You'll want to cache the info somewhere.
The way to get the exact information you're after is to call
GetType().GetMethod(...) to get a MethodInfo, and check to see if the
DeclaringType is equal to the base type. If it isn't, then it's
overridden. For example:
---8<---
using System;
using System.Reflection;
class Program
{
class A
{
public virtual void Foo() { }
public virtual void Bar() { }
}
class B : A
{
public override void Foo() { }
}
static void Main(string[] args)
{
B b = new B();
MethodInfo foo = b.GetType().GetMethod("Foo");
MethodInfo bar = b.GetType().GetMethod("Bar");
Console.WriteLine(foo.DeclaringType);
Console.WriteLine(bar.DeclaringType);
}
}
--->8---
> Bool a and b are complex to calculate so I don't want to calculate them
> unless I need to
Why not put them both as properties in some inner class (say
ExpensiveArguments.A and .B) and have them evaluate on demand, in a
call-by-name way? If you're using C# 2.0, you could pass in anonymous
delegates so that the values get calculated in the context of the
caller. This is what I would do.
It would also give an opportunity to the overriders to avoid evaluating
the expensive arguments if they don't need one or both of them.
-- Barry
--
http://barrkel.blogspot.com/