Created
November 8, 2012 20:59
-
-
Save dgroft/4041555 to your computer and use it in GitHub Desktop.
A constructor for immutable types that takes a dynamic list of parameters
This file contains hidden or 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
protected MyImmutableObject(IDictionary<string, object> parameters) | |
{ | |
foreach (var field in GetType().GetFields().Where(x => parameters.Keys.Contains(x.Name))) | |
{ | |
if (parameters[field.Name] is Dictionary<string, object>) | |
{ | |
var ctor = field.FieldType.GetConstructor(new[] { typeof(Dictionary<string, object>) }); | |
var instance = ctor.Invoke(new object[] { parameters[field.Name] }); | |
field.SetValue(this, instance); | |
} | |
else | |
{ | |
field.SetValue(this, TypeDescriptor.GetConverter(field.FieldType).ConvertFrom(parameters[field.Name].ToString())); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment