I was recently working on a project where the use of reflection became one of the proposed solutions. Before I go any further, allow me to preface this by saying that reflection can be costly and have negative performance impacts. It is not always type safe and may lead to run-time exceptions. Other alternatives should be considered before committing to using reflection as a solution.
The scenario we had was we needed to access a private method inside a legacy .NET assembly. I'm not going to get into the reasons why. The alternative was to duplicate all of the logic that was needed from legacy code. I mentioned to a co-worker that we could use reflection to invoke a private method. He was skeptical so I provided him with the following spike solution code showing how to do just that. It's a simple, but complete working example that I thought I would share with all of you.
- using System;
- using System.Collections.Generic;
- using System.Reflection;
- namespace ConsoleApplication1 {
- class Program {
- static void Main(string[] args) {
- HelloWorld hw = new HelloWorld();
- hw.SayWhatsUp();
- hw.name = "World";
- BindingFlags eFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
- MethodInfo hi = null;
- hi = hw.GetType().GetMethod("SayHi", eFlags);
- object[] a = new List<object>().ToArray();
- if (hi != null) {
- hi.Invoke(hw, a);
- } else {
- Console.WriteLine("Method Not Found.");
- }
- Console.ReadLine();
- }
- }
- public class HelloWorld {
- public string name { get; set; }
- public void SayWhatsUp() {
- Console.WriteLine("Whats Up");
- }
- private void SayHi() {
- Console.WriteLine("Hi " + name);
- }
- }
- }
0 comments:
Post a Comment