Created
March 6, 2020 16:52
-
-
Save decay88/5a153028b33b3c56cea16208d4bc462b to your computer and use it in GitHub Desktop.
Invoker.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Invoker : DynamicObject, IDynamicMetaObjectProvider{ | |
Type InstanceType | |
public Invoker(object instance) | |
{ | |
Initialize(instance); | |
} | |
protected void Initialize(object instance) | |
{ | |
Instance = instance; | |
if (instance != null) | |
InstanceType = instance.GetType(); | |
} | |
protected bool InvokeMethod(object instance, string name, object[] args, out object result) | |
{ | |
if (instance == null) | |
instance = this; | |
// Look at the instanceType | |
var miArray = InstanceType.GetMember(name, | |
BindingFlags.InvokeMethod | | |
BindingFlags.Public | BindingFlags.Instance); | |
if (miArray != null && miArray.Length > 0) | |
{ | |
var mi = miArray[0] as MethodInfo; | |
result = mi.Invoke(Instance, args); | |
return true; | |
} | |
result = null; | |
return false; | |
} | |
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) | |
{ | |
if (Instance != null) | |
{ | |
try | |
{ | |
// check instance passed in for methods to invoke | |
if (InvokeMethod(Instance, binder.Name, args, out result)) | |
return true; | |
} | |
catch { } | |
} | |
result = null; | |
return false; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment