Last active
August 29, 2015 14:02
-
-
Save Fhernd/bd7a41a1f2b74e41935e to your computer and use it in GitHub Desktop.
Demostración de la declaración de una clase dinámica en C#.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Dynamic; | |
namespace Receptas.Cap04 | |
{ | |
public class DiccionarioDinamico : DynamicObject | |
{ | |
private IDictionary<string, object> dict = new Dictionary<string, object>(); | |
// Propiedad estática: | |
public int Contador | |
{ | |
get | |
{ | |
Console.WriteLine ("Se ha invocado la propiedad `Contador`."); | |
return dict.Count; | |
} | |
} | |
public override bool TryGetMember (GetMemberBinder binder, out object result) | |
{ | |
Console.WriteLine ("Solicitud de miembro dinámico: {0}", binder.Name); | |
return dict.TryGetValue (binder.Name, out result); | |
} | |
public override bool TrySetMember (SetMemberBinder binder, object value) | |
{ | |
Console.WriteLine ("Solicitud de establecimiento de valor {0} para el miembro {1}", | |
binder.Name, value); | |
dict[binder.Name] = value; | |
return true; | |
} | |
} | |
public sealed class PruebaDiccionarioDinamico | |
{ | |
public static void Main() | |
{ | |
// Declaración variable dynamic: | |
dynamic dynDict; | |
// Encapsulación de variable de `DiccionarioDinamico` sobre | |
// la variable `dynDict`: | |
dynDict = new DiccionarioDinamico(); | |
// Creación dinámica de propiedades, y asignación | |
// de valores: | |
Console.WriteLine ("\nCreación de propiedades y asignación valores:"); | |
dynDict.PrimerNombre = "John"; | |
dynDict.Apellido = "Ortiz"; | |
// Recuperación de valores de propiedades: | |
Console.WriteLine ("\nObtención de los valores de las propiedades dinámicas:"); | |
Console.WriteLine ("\tPrimer nombre: {0}", dynDict.PrimerNombre); | |
Console.WriteLine ("\tApellido: {0}", dynDict.Apellido); | |
// Invocación de miembro declarado estáticamente: | |
Console.WriteLine ("\nInvocación de miembro declarado estáticamente:"); | |
Console.WriteLine ("\tContador: {0}", dynDict.Contador.ToString()); | |
// Intento de invocación de una propiedad no existente: | |
Console.WriteLine ("\nIntento de invocar propiedad no existente:"); | |
try | |
{ | |
Console.WriteLine ("\tCiudad {0}", dynDict.Ciudad); | |
} | |
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) | |
{ | |
Console.WriteLine ("\tLa propiedad `Ciudad` no ha sido declarada ni estática ni dinámicamente."); | |
} | |
Console.WriteLine(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment