Advertisement
Termininja

Initialize Dynamic class with Constructor

Apr 8th, 2018
620
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.00 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Dynamic;
  5.  
  6. class Program
  7. {
  8.     static void Main()
  9.     {
  10.         var fields = new List<Field>() {
  11.             new Field("EmployeeID", typeof(int)),
  12.             new Field("EmployeeName", typeof(string)),
  13.             new Field("Designation", typeof(string))
  14.         };
  15.  
  16.         //set
  17.         dynamic obj = new DynamicClass(fields, new {EmployeeID = 123456, EmployeeName = "John", Designation = "Tech Lead"});
  18.  
  19.         //get
  20.         Console.WriteLine(obj.EmployeeID);
  21.         Console.WriteLine(obj.EmployeeName);
  22.         Console.WriteLine(obj.Designation);
  23.     }
  24. }
  25.  
  26. public class DynamicClass : DynamicObject
  27. {
  28.     private Dictionary<string, KeyValuePair<Type, object>> _fields;
  29.  
  30.     public DynamicClass(List<Field> fields, object props)
  31.     {
  32.         _fields = new Dictionary<string, KeyValuePair<Type, object>>();
  33.         var properties = props.GetType().GetProperties();
  34.         foreach (var p in properties)
  35.         {
  36.             var element = fields.FirstOrDefault(x => x.FieldName == p.Name);
  37.             if (element != null)
  38.             {
  39.                 var value = p.GetValue(props, null);
  40.                 if (value.GetType() == element.FieldType)
  41.                 {
  42.                     _fields.Add(p.Name, new KeyValuePair<Type, object>(element.FieldType, value));
  43.                 }
  44.                 else throw new Exception("Value " + value + " is not of type " + element.FieldType.Name);
  45.             }
  46.             else throw new Exception(this.GetType().Name + " does not contain a definition for '" + p.Name + "'");
  47.         }
  48.     }
  49.  
  50.     public override bool TryGetMember(GetMemberBinder binder, out object result)
  51.     {
  52.         result = _fields[binder.Name].Value;
  53.         return true;
  54.     }
  55. }
  56.  
  57. public class Field
  58. {
  59.     public Field(string name, Type type)
  60.     {
  61.         this.FieldName = name;
  62.         this.FieldType = type;
  63.     }
  64.  
  65.     public string FieldName;
  66.  
  67.     public Type FieldType;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement