Reputation: 3406
I have following generic method in C# that parses client data from an ASP.NET web forms application into some defined type:
public static T ParseClientRequest <T> (object data)
{
var t = (System.Collections.Generic.Dictionary<string,object>) data;
T obj = (T)Activator.CreateInstance(typeof(T));
foreach(var pair in t) {
FieldInfo field = obj.GetType().GetField(pair.Key);
field.SetValue(obj, pair.Value);
}
return obj;
}
I have two questions about it:
Upvotes: 1
Views: 106
Reputation: 12546
1- Efficiency is relative. Hard to answer. If it is good enough for you, then no problem
2- You can fix your code by using Convert.ChangeType
public static T ParseClientRequest<T>(object data)
{
var t = (System.Collections.Generic.Dictionary<string, object>)data;
T obj = (T)Activator.CreateInstance(typeof(T));
foreach (var pair in t)
{
FieldInfo field = obj.GetType().GetField(pair.Key);
field.SetValue(obj, Convert.ChangeType(pair.Value, field.FieldType)); //See this line
}
return obj;
}
Upvotes: 2