Skip to content

Instantly share code, notes, and snippets.

@JimmyHoffa
Created August 27, 2014 21:12
Show Gist options
  • Save JimmyHoffa/4e69aafc6ab17df4879e to your computer and use it in GitHub Desktop.
Save JimmyHoffa/4e69aafc6ab17df4879e to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LogicInTypeSystem
{
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Phone { get; set; }
}
public class PeoplesPhones
{
public string Name { get; set; }
public string Phone { get; set; }
}
public class PeoplesAges
{
public string Name { get; set; }
public int Age { get; set; }
}
public static class PersonGetter
{
static PersonGetter()
{
// at some point around application initialize you need to instantiate your static PersonMap<T> instances...
PersonMap<PeoplesPhones>.MappingFunc = (person) => new Person { Name = person.Name, Phone = person.Phone };
PersonMap<PeoplesAges>.MappingFunc = (person) => new Person { Name = person.Name, Age = person.Age };
}
private static class PersonMap<T>
{
public static Func<T, Person> MappingFunc { get; set; }
}
public static Person GetPerson<T>(this T target)
{
return PersonMap<T>.MappingFunc(target);
}
}
class Program
{
static void Main(string[] args)
{
PeoplesPhones phone = new PeoplesPhones { Name = "Foo", Phone = "Bar" };
PeoplesAges age = new PeoplesAges { Name = "ooF", Age = 42 };
Person personA = phone.GetPerson();
Person personB = age.GetPerson();
Console.WriteLine("Name: {0}, Age: {1}, Phone: {2}", personA.Name, personA.Age, personA.Phone);
Console.WriteLine("Name: {0}, Age: {1}, Phone: {2}", personB.Name, personB.Age, personB.Phone);
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment