3

Take a look at setAccessible - a way in Java to let you call private methods by reflections. Why didn't .NET implement such a feature yet?

Community
  • 1
  • 1
ripper234
  • 222,824
  • 274
  • 634
  • 905

4 Answers4

6

Here is an example of doing that in .NET

using System;
using System.Reflection;
using System.Collections.Generic;

public class MyClass
{
   public static void Main()
   {
        try
        {
            Console.WriteLine("TestReflect started.");
            TestReflect test = new TestReflect();
            Console.WriteLine("TestReflect ended.");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }

        ConsoleKeyInfo cki;
        do
        {
            Console.WriteLine("Press the 'Q' key to exit.");
            cki = Console.ReadKey(true);
        } while (cki.Key != ConsoleKey.Q);
   }
}

public class TestReflect
{
   public TestReflect()
   {
        this.GetType().GetMethod("PublicMethod").Invoke(this, null);
        this.GetType().GetMethod("PrivateMethod", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(this, null);
   }

   public void PublicMethod()
   {
        Console.WriteLine("PublicMethod called");
   }

   private void PrivateMethod()
   {
        Console.WriteLine("FTW!one1");
   }
 }
Yishai
  • 90,445
  • 31
  • 189
  • 263
4

You can use reflection to call private methods, though it isn't as straight forward as calling public methods. We've done this before for unit testing and have used the following posts as a how-to reference:

http://www.emadibrahim.com/2008/07/09/unit-test-private-methods-in-visual-studio/

http://johnhann.blogspot.com/2007/04/unit-testing-private-methods.html

James Conigliaro
  • 3,809
  • 19
  • 22
2

I think "why" might be a bit of a speculative question, but if you are looking for a way to test private methods, I think you'll be able to do this easier with .NET 4.0:

http://bugsquash.blogspot.com/2009/05/testing-private-methods-with-c-40.html

Matthew Groves
  • 25,181
  • 9
  • 71
  • 121
2

It's quite possible in .NET to get access to anything private using reflection.

E.g getting acces to a private instance method called Foo on class bar would look like:

typeof(Bar).GetMethod("Foo",BindingFlags.NonPublic | BindingFlags.Instance);

it does however require that the code using reflection is fully trusted.

(The security requirements will be different for V4)

Rune FS
  • 21,497
  • 7
  • 62
  • 96