Advertisement
Guest User

NonPublic Method Invocation - Part #2

a guest
Jan 5th, 2012
1,326
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.01 KB | None | 0 0
  1. // Invoker.cs
  2.  
  3. namespace Reflection
  4. {
  5.     using System;
  6.     using System.Collections.Generic;
  7.     using System.Reflection;
  8.  
  9.     public class Invoker
  10.     {
  11.         private readonly Dictionary<Type, InvocationMember> mInvocationList = new Dictionary<Type, InvocationMember>();
  12.  
  13.         public void Register(object target, params string[] methodNames)
  14.         {
  15.             Type type = target.GetType();
  16.  
  17.             InvocationMember member;
  18.             if (!mInvocationList.TryGetValue(type, out member))
  19.             {
  20.                 mInvocationList.Add(type, (member = new InvocationMember(target, type)));
  21.             }
  22.  
  23.             member.MethodNames.AddRange(methodNames);
  24.         }
  25.  
  26.         public IEnumerable<string> GetResults()
  27.         {
  28.             foreach (var member in mInvocationList.Values)
  29.             {
  30.                 object target = member.Target;
  31.                 Type type = member.Type;
  32.  
  33.                 foreach (string methodName in member.MethodNames)
  34.                 {
  35.                     object result;
  36.  
  37.                     try
  38.                     {
  39.                         result = type.InvokeMember(methodName, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
  40.                                                    Type.DefaultBinder, target, null);
  41.                     }
  42.                     catch (Exception ex)
  43.                     {
  44.                         result = string.Format("Error: {0}", ex.Message);
  45.                     }
  46.  
  47.                     yield return (result as string) ?? "<null>";
  48.                 }
  49.             }
  50.         }
  51.  
  52.         private class InvocationMember
  53.         {
  54.             public readonly object Target;
  55.             public readonly Type Type;
  56.             public readonly List<string> MethodNames = new List<string>();
  57.  
  58.             public InvocationMember(object target, Type type)
  59.             {
  60.                 this.Target = target;
  61.                 this.Type = type;
  62.             }
  63.         }
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement