El rincón de JMACOE

¿Cómo acceder e invocar a una función protegida o privada?

.Net Framework nos permite acceso protegido y privado a funciones y datos de un objeto utilizando los servicios del Namespace, y este simple código muestra cómo acceder a una función privada e invocarla.

Código Vb.Net:

Module Module1
    Sub Main()
        ' Our object that contains the private function we will call through reflection
        Dim tst As New Test()
        ' Get the type of the object
        Dim t As Type = tst.GetType()
        ' Retrieve the method info of the function Test.PrivateSub
        Dim mtd As Reflection.MethodInfo = t.GetMethod("PrivateSub", Reflection.BindingFlags.Instance Or Reflection.BindingFlags.InvokeMethod Or Reflection.BindingFlags.NonPublic)
        ' Invoke the private methode. This should print : <> on the console window
        mtd.Invoke(tst, Nothing)
    End Sub
 
    ' Our test class
    Class Test
        ' Our private function that we will try calling from outside
        Private Sub PrivateSub()
            Console.WriteLine("PrivateSub reached from out side!")
        End Sub
    End Class
End Module

Código C#:

using System;
using System.Reflection;
 
namespace ConsoleApplication1
{
    class Program
    {
        public static void Main()
        {
            // Our object that contains the private function we will call through reflection
            Test tst = new Test();
            // Get the type of the object
            Type t = tst.GetType();
            // Retrieve the method info of the function Test.PrivateSub
            MethodInfo mtd = t.GetMethod("PrivateSub", BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.NonPublic);
            // Invoke the private methode. This should print : <> on the console window
            mtd.Invoke(tst, null);
        }
 
        // Our test class
        public class Test
        {
            // Our private function that we will try calling from outside
            private void PrivateSub()
            {
                Console.WriteLine("PrivateSub reached from out side!");
            }
        }
    }
}

Podemos utilizar el mismo truco para acceso a datos y propiedades de sólo lectura, privados y protegidos. Eso es lo que vamos a ver el próximo post…

Comparte y diviertete: