Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace ConsoleApplication1
- {
- using System;
- using System.Diagnostics;
- using System.IO;
- using System.Linq.Expressions;
- using System.Reflection;
- public class Program
- {
- private static void Main(string[] args)
- {
- var m = new Model();
- var s = new MemoryStream();
- var sw = Stopwatch.StartNew();
- for (var i = 0; i < 1000000; i++)
- {
- Test.Write(s, m);
- }
- Console.WriteLine("{0} ms", sw.ElapsedMilliseconds);
- var ex = new ExplicitHandler<Model>();
- sw.Restart();
- for (var i = 0; i < 1000000; i++)
- {
- ex.Write(s, m);
- }
- Console.WriteLine("{0} ms", sw.ElapsedMilliseconds);
- }
- }
- public class HandlerFactory
- {
- public static IHandler<T> Create<T>()
- {
- return new ExplicitHandler<T>();
- }
- }
- public interface IHandler<T>
- {
- T Read(Stream s);
- void Write(Stream s, T v);
- }
- public interface IHandler
- {
- object Read(Stream s);
- void Write(Stream s, object v);
- }
- public class Model
- {
- }
- public class ExplicitHandler<T> : IHandler<T>, IHandler
- {
- public T Read(Stream s)
- {
- return default(T);
- }
- public void Write(Stream s, T v)
- {
- }
- void IHandler.Write(Stream s, object v)
- {
- Write(s, (T)v);
- }
- object IHandler.Read(Stream s)
- {
- return Read(s);
- }
- }
- public class Test
- {
- static Dictionary<Type, IHandler> delegates = new Dictionary<Type, IHandler>();
- public static void Write(MemoryStream s, object value)
- {
- IHandler handler;
- var type = value.GetType();
- if (!delegates.TryGetValue(type, out handler))
- {
- handler = (IHandler)typeof(HandlerFactory).GetMethod(nameof(HandlerFactory.Create)).MakeGenericMethod(type).Invoke(null, null);
- delegates[type] = handler;
- }
- handler.Write(s, value);
- }
- }
- }
Add Comment
Please, Sign In to add comment