Created
August 26, 2011 14:39
-
-
Save ilkerde/1173541 to your computer and use it in GitHub Desktop.
A quick prototype for a shallow copy of an object with changing values ;-)
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
add-type @" | |
using System; | |
using System.Linq; | |
public class A { | |
public A() { Age = 40; Name = "DerAlbert"; Type = "Original"; } | |
public int Age { get; set; } | |
public string Name { get; set; } | |
public string Type { get; set; } | |
public A With(object o) { | |
var matches = from otherProperty in o.GetType().GetProperties() | |
join myProperty in typeof(A).GetProperties() on otherProperty.Name equals myProperty.Name | |
select new { Mine = myProperty, Yours = otherProperty }; | |
A clone = this.MemberwiseClone() as A; | |
foreach (var match in matches) | |
match.Mine.SetValue(clone, match.Yours.GetValue(o, null), null); | |
return clone; | |
} | |
} | |
public class O { | |
public O() { Age = 30; Name = "forki"; Type = "Funky"; } | |
public int Age { get; set; } | |
public string Name { get; set; } | |
public string Type { get; set; } | |
} | |
public static class Testing { | |
public static A Anonymous() { | |
A a = new A(); | |
return a.With(new {Name = "ilkerde", Age = 35, Type = "Dynamic"}); | |
} | |
} | |
"@ -lang csharpversion3 | |
$o = new-object O | |
$a = new-object A | |
# @forki: is it that what you wanted? ;-) | |
$b = $a.With($o) | |
$c = [Testing]::Anonymous(); | |
$a | |
$b | |
$c |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment