Created
December 3, 2010 02:52
-
-
Save aaronpowell/726511 to your computer and use it in GitHub Desktop.
Makes an anonymous type implement an interface
This file contains 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
//uses ClaySharp: http://clay.codeplex.com | |
//add the following usings | |
//using ClaySharp; | |
//using ClaySharp.Behaviors; | |
void Main() | |
{ | |
var foo = TypeMe<IFoo>(new { Id = 1, Name = "Aaron" }); | |
Console.WriteLine(foo.Id); | |
Console.WriteLine(foo.Name); | |
} | |
// Define other methods and classes here | |
public interface IFoo { | |
int Id { get; set; } | |
string Name { get; set; } | |
} | |
public static T TypeMe<T>(object o) { | |
dynamic clay = new Clay(new PropBehavior(), new InterfaceProxyBehavior()); | |
T v = clay; | |
var properties = o.GetType().GetProperties(); | |
foreach(var p in properties) { | |
var x = v.GetType().GetProperty(p.Name); | |
if(x != null) { | |
x.SetValue(v, p.GetValue(o, null), null); | |
} | |
} | |
return v; | |
} | |
public static T As<T>(this object o) { | |
return TypeMe<T>(o); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment