// Invoker.cs
namespace Reflection
{
using System;
using System.Collections.Generic;
using System.Reflection;
public class Invoker
{
private readonly Dictionary<Type, InvocationMember> mInvocationList = new Dictionary<Type, InvocationMember>();
public void Register(object target, params string[] methodNames)
{
Type type = target.GetType();
InvocationMember member;
if (!mInvocationList.TryGetValue(type, out member))
{
mInvocationList.Add(type, (member = new InvocationMember(target, type)));
}
member.MethodNames.AddRange(methodNames);
}
public IEnumerable<string> GetResults()
{
foreach (var member in mInvocationList.Values)
{
object target = member.Target;
Type type = member.Type;
foreach (string methodName in member.MethodNames)
{
object result;
try
{
result = type.InvokeMember(methodName, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
Type.DefaultBinder, target, null);
}
catch (Exception ex)
{
result = string.Format("Error: {0}", ex.Message);
}
yield return (result as string) ?? "<null>";
}
}
}
private class InvocationMember
{
public readonly object Target;
public readonly Type Type;
public readonly List<string> MethodNames = new List<string>();
public InvocationMember(object target, Type type)
{
this.Target = target;
this.Type = type;
}
}
}
}