ripper234 ripper234 - 1 month ago 9
Java Question

Why isn't there a parallel to Java's setAccessible in .NET?

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?

Answer

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");
   }
 }
Comments