Created
April 1, 2010 20:07
-
-
Save statianzo/352304 to your computer and use it in GitHub Desktop.
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
//Anonymous Mapper | |
//Map any object to an anonymous type | |
public static T AnonMap<T>(this object source, T anonType) | |
{ | |
var sourceType = source.GetType(); | |
var destinationType = typeof(T); | |
if (!destinationType.Name.StartsWith("<>")) | |
throw new ArgumentException("Destination type must be anonymous", "anonType"); | |
var ctor = destinationType.GetConstructors().First(); | |
var args = new List<object>(); | |
foreach (var p in ctor.GetParameters()) | |
{ | |
var foundProp = sourceType.GetProperty(p.Name); | |
if (foundProp != null) | |
args.Add(foundProp.GetValue(source, null)); | |
else if (p.ParameterType.IsValueType) | |
args.Add(Activator.CreateInstance(p.ParameterType)); | |
else | |
args.Add(null); | |
} | |
var instance = Activator.CreateInstance(destinationType, args.ToArray()); | |
return (T)instance; | |
} | |
//Usage | |
public void CanAnonCast() | |
{ | |
var original = GiveAnon(); | |
var casted = original.AnonMap(new { Name = default(string), Age = default(int) }); | |
Assert.AreEqual(26, casted.Age); | |
Assert.AreEqual("Sweet", casted.Name); | |
} | |
private object GiveAnon() | |
{ | |
return new { Name = "Sweet", Age = 26 }; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment