From ba24707b18ea9fbb415f3dcdf2707f4e9b9656f2 Mon Sep 17 00:00:00 2001 From: Ellpeck Date: Fri, 31 Jul 2020 19:07:22 +0200 Subject: [PATCH] added object copying to MLEM.Data --- MLEM.Data/CopyExtensions.cs | 37 +++++++++++++++++++++++++++++++++++++ Sandbox/GameImpl.cs | 10 +++++++++- 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 MLEM.Data/CopyExtensions.cs diff --git a/MLEM.Data/CopyExtensions.cs b/MLEM.Data/CopyExtensions.cs new file mode 100644 index 0000000..dbe03b9 --- /dev/null +++ b/MLEM.Data/CopyExtensions.cs @@ -0,0 +1,37 @@ +using System; +using System.Reflection; + +namespace MLEM.Data { + /// + /// A set of extensions for dealing with copying objects. + /// + public static class CopyExtensions { + + /// + /// Creates a shallow copy of the object and returns it. + /// Note that, for this to work correctly, needs to contain a parameterless constructor. + /// + /// The object to create a shallow copy of + /// The binding flags for field searching + /// The type of the object to copy + /// A shallow copy of the object + public static T Copy(this T obj, BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) { + var copy = (T) typeof(T).GetConstructor(Type.EmptyTypes).Invoke(null); + obj.CopyInto(copy, flags); + return copy; + } + + /// + /// Copies the given object into the given object . + /// + /// The object to create a shallow copy of + /// The object to copy into + /// The binding flags for field searching + /// The type of the object to copy + public static void CopyInto(this T obj, T otherObj, BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) { + foreach (var field in typeof(T).GetFields(flags)) + field.SetValue(otherObj, field.GetValue(obj)); + } + + } +} \ No newline at end of file diff --git a/Sandbox/GameImpl.cs b/Sandbox/GameImpl.cs index bb9e9a1..9012b2f 100644 --- a/Sandbox/GameImpl.cs +++ b/Sandbox/GameImpl.cs @@ -96,6 +96,14 @@ namespace Sandbox { RectangleF = new RectangleF(4, 5, 6, 7).ToMlem(), Dir = Direction2.Left }; + Console.WriteLine(obj); + + var copy = obj.Copy(); + Console.WriteLine(copy); + + var intoCopy = new Test(); + obj.CopyInto(intoCopy); + Console.WriteLine(intoCopy); var writer = new StringWriter(); this.Content.GetJsonSerializer().Serialize(writer, obj); @@ -208,7 +216,7 @@ namespace Sandbox { public Point Point; public Rectangle Rectangle; public MLEM.Misc.RectangleF RectangleF; - public Direction2 Dir; + public Direction2 Dir { get; set; } public override string ToString() { return $"{nameof(this.Vec)}: {this.Vec}, {nameof(this.Point)}: {this.Point}, {nameof(this.Rectangle)}: {this.Rectangle}, {nameof(this.RectangleF)}: {this.RectangleF}, {nameof(this.Dir)}: {this.Dir}";