Inicio > Programacion > ¿Cómo escribir propiedades de sólo lectura y los valores de los campos?

¿Cómo escribir propiedades de sólo lectura y los valores de los campos?

domingo, 25 de febrero de 2024 Dejar un comentario Ir a comentarios

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:

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

Código C#:

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;
                }
            }
        }
    }
}

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!

Comparte y diviertete:
  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • BarraPunto
  • Bitacoras.com
  • BlinkList
  • Blogosphere
  • Live
  • Meneame
  • MSN Reporter
  • MySpace
  • RSS
  • Suggest to Techmeme via Twitter
  • Technorati
  • LinkedIn
  • email
  • FriendFeed
  • PDF
  • Reddit
  • Wikio IT
  • Add to favorites
  • blogmarks
Categories: Programacion Tags: , , ,
Top Footer