forked from scriptcs/scriptcs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrinters.cs
More file actions
42 lines (37 loc) · 1.09 KB
/
Printers.cs
File metadata and controls
42 lines (37 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
using System;
using System.Collections.Generic;
namespace ScriptCs.Contracts
{
public class Printers
{
private readonly IObjectSerializer _serializer;
private readonly Dictionary<Type, Func<object, string>> _dictionary = new Dictionary<Type, Func<object, string>>();
public Printers(IObjectSerializer serializer)
{
_serializer = serializer;
}
public void AddCustomPrinter<T>(Func<T, string> printer)
{
_dictionary[typeof(T)] = x => printer((T)x);
}
private string GetStringFor(Type t, object obj)
{
Func<object, string> printer;
if (_dictionary.TryGetValue(t, out printer))
{
return printer(obj);
}
else {
return _serializer.Serialize(obj);
}
}
public string GetStringFor(object obj)
{
return GetStringFor(obj.GetType(), obj);
}
public string GetStringFor<T>(T obj)
{
return GetStringFor(typeof(T), obj);
}
}
}