¿Cómo escribir propiedades de sólo lectura y los valores de los campos?
Como hemos visto juntos en un anterior post, .NET Framework nos permite acceder e invocar funciones protegidas y privadas de un objeto. En este post, veremos la forma de escribir propiedades de sólo lectura con los servicios del Namespace Reflection.
El código es tan simple como el anterior y comentado en su totalidad.
Código Vb.Net:
[vbnet]
Module Module1
Sub Main()
‘ The object that contains the read-only field
Dim tst As New Test()
‘ Just a test
Console.WriteLine(tst.ReadOnlyProperty)
‘ Get the type of the object
Dim t As Type = tst.GetType()
‘ Get the field info object
Dim fi As Reflection.FieldInfo = t.GetField("ReadOnlyPropertyValue", Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance)
‘ Write the read-only field/propertie value
fi.SetValue(tst, "I changed it!")
‘ Check the new value
Console.WriteLine(tst.ReadOnlyProperty)
End Sub
‘ The class that contains the read-only propertie/field
Public Class Test
Sub New()
‘ Set the value of the field/propertie (internal)
ReadOnlyPropertyValue = "This must never change from out side!"
End Sub
‘ The internal private value
Private ReadOnlyPropertyValue As String
‘ The read-only propertie we want to write the value
Public ReadOnly Property ReadOnlyProperty() As String
Get
Return ReadOnlyPropertyValue
End Get
End Property
End Class
End Module
[/vbnet]
Código C#:
[csharp]
using System;
using System.Reflection;
namespace ConsoleApplication1
{
class Program
{
public static void Main()
{
// The object that contains the read-only field
Test tst = new Test();
// Just a test
Console.WriteLine(tst.ReadOnlyProperty);
// Get the type of the object
Type t = tst.GetType();
// Get the field info object
FieldInfo fi = t.GetField("readOnlyPropertyValue", BindingFlags.Instance | BindingFlags.NonPublic);
// Write the read-only field/propertie value
fi.SetValue(tst, "I changed it!");
// Check the new value
Console.WriteLine(tst.ReadOnlyProperty);
}
// The class that contains the read-only propertie/field
public class Test
{
public Test()
{
// Set the value of the field/propertie (internal)
readOnlyPropertyValue = "This must not be changed from outside!";
}
// The internal private value
private string readOnlyPropertyValue;
// The read-only propertie we want to write the value
public string ReadOnlyProperty
{
get {
return readOnlyPropertyValue;
}
}
}
}
}
[/csharp]
Algunas veces, puedes necesitar cambiar las propiedades de sólo lectura/valores de los campos para depuración y propósitos de prueba.
Intenta cambiar los valores estándar de sólo lectura de los objetos del Framework .Net, ¡pueden dar resultados imprevisibles!