Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Dynamic;
- class Program
- {
- static void Main()
- {
- var fields = new List<Field>() {
- new Field("EmployeeID", typeof(int)),
- new Field("EmployeeName", typeof(string)),
- new Field("Designation", typeof(string))
- };
- //set
- dynamic obj = new DynamicClass(fields, new {EmployeeID = 123456, EmployeeName = "John", Designation = "Tech Lead"});
- //get
- Console.WriteLine(obj.EmployeeID);
- Console.WriteLine(obj.EmployeeName);
- Console.WriteLine(obj.Designation);
- }
- }
- public class DynamicClass : DynamicObject
- {
- private Dictionary<string, KeyValuePair<Type, object>> _fields;
- public DynamicClass(List<Field> fields, object props)
- {
- _fields = new Dictionary<string, KeyValuePair<Type, object>>();
- var properties = props.GetType().GetProperties();
- foreach (var p in properties)
- {
- var element = fields.FirstOrDefault(x => x.FieldName == p.Name);
- if (element != null)
- {
- var value = p.GetValue(props, null);
- if (value.GetType() == element.FieldType)
- {
- _fields.Add(p.Name, new KeyValuePair<Type, object>(element.FieldType, value));
- }
- else throw new Exception("Value " + value + " is not of type " + element.FieldType.Name);
- }
- else throw new Exception(this.GetType().Name + " does not contain a definition for '" + p.Name + "'");
- }
- }
- public override bool TryGetMember(GetMemberBinder binder, out object result)
- {
- result = _fields[binder.Name].Value;
- return true;
- }
- }
- public class Field
- {
- public Field(string name, Type type)
- {
- this.FieldName = name;
- this.FieldType = type;
- }
- public string FieldName;
- public Type FieldType;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement