synthroid taking instructions

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

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

miércoles, 11 de diciembre de 2024 Dejar un comentario Ir a comentarios

.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:

[vbnet]
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
[/vbnet]

Código C#:

[csharp]
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!");
}
}
}
}
[/csharp]

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…

Categories: Programacion Tags: , , , ,
  1. Sin comentarios aún.
  1. Sin trackbacks aún.