views:

48

answers:

2

Lets say i call method M1 on class A using reflection. The method does not exist.

Is there any way to put a handler on class A that says, "someone is trying to execute method M1"?

Or

Is it possible to add a method dinamically to a class? I want to add a method M1...Mn that always does MyStaticClass.DoAction("M1...Mn");

Something like:

string methodName = "M1".

A.AddMethod(methodname,x => MyStaticClass.DoAction(x));

Thanks

+1  A: 

You need the DLR, specifically DynamicObject.TryInvokeMember. Essentially, you override DynamicObject with as many regular members as you want, and then provide TryInvokeMember to handle other method calls at runtime

Matthew Flaschen
Nice, i got it. Is it required to use VS2010 to use C# 4.0 ?
Joaozinho das Couves
No. Mono already has basic support for System.Dynamic.
Matthew Flaschen
A: 

There is actually a realy easy way to do this in C# 4.0.. dunno what framework you are using.

This should get you an headstart .. but remember you have to declare a bit more just to make your code safe.

class DynamicTester : DynamicObject
{
    public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
    {
        Console.WriteLine("Someone is calling method {0}", binder.Name); result = null; return true;
    }
    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        Console.WriteLine("Someone is trying to get attribute {0}", binder.Name); result = null; return true;
    }
    public override bool TrySetMember(SetMemberBinder binder, object value) 
    {
        Console.WriteLine("Someone is trying to set attribute {0} to value {1}", binder.Name, Convert.ToString(value)); return true;
    }
}
class Program
{
    static void Main(string[] args)
    {
        dynamic dt = new DynamicTester();
        dt.A = "Test"; dt.B = 14; dt.date = DateTime.Now;
        var i = dt.Z;
        dt.Tester(1, 2, 3);
    }
}

The key part is to use dynamic as data type. That will mark it not to try to resolve method/attribute calls at compile time but at runtime even with your own code.

simplifies a lot the whole refactoring that had to be done before.

ilandra