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 dynamically 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(met开发者_JS百科hodname,x => MyStaticClass.DoAction(x));
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.
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
精彩评论