Last active
August 19, 2016 08:48
-
-
Save callerobertsson/989ded86ee35d1adaf06 to your computer and use it in GitHub Desktop.
C#: True down cast from child to parent using JSON
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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using Newtonsoft.Json; | |
namespace DownCaster | |
{ | |
static class Program | |
{ | |
static void Main() | |
{ | |
var child = new Child | |
{ | |
InParentAndChild = "foo", | |
OnlyInChild = "bar", | |
Items = new List<SubItem> | |
{ | |
new SubItem | |
{ | |
InItemAndItemChild = "fuz", | |
OnlyInSubItem = "baz" | |
} | |
} | |
}; | |
Console.WriteLine("Child: " + JsonConvert.SerializeObject(child)); | |
var parent = child.DowncastToBase(); | |
Console.WriteLine("Parent: " + JsonConvert.SerializeObject(parent)); | |
Console.ReadLine(); | |
} | |
} | |
public class Parent | |
{ | |
public string InParentAndChild { get; set; } | |
public IList<Item> Items { get; set; } | |
} | |
public class Child : Parent | |
{ | |
public string OnlyInChild { get; set; } | |
public new IList<SubItem> Items { get; set; } | |
} | |
public class Item | |
{ | |
public string InItemAndItemChild { get; set; } | |
} | |
public class SubItem : Item | |
{ | |
public string OnlyInSubItem { get; set; } | |
} | |
public static class DowncastExtensions | |
{ | |
public static Parent DowncastToBase(this Child c) | |
{ | |
var json = JsonConvert.SerializeObject(c); | |
var parent = JsonConvert.DeserializeObject<Parent>(json); | |
parent.Items = c.Items.Select(i => i.DowncastToBase()).ToList(); | |
return parent; | |
} | |
public static Item DowncastToBase(this SubItem si) | |
{ | |
var json = JsonConvert.SerializeObject(si); | |
return JsonConvert.DeserializeObject<Item>(json); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this is very slow