Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Program
- {
- // Can't do IDictionary<int, Func<T, String>> as T is not available here.
- private static readonly IDictionary<int, Object> _cache = new Dictionary<int, Object>();
- public static void SomeToStringCalls()
- {
- Console.WriteLine(ToString(i => (i + 1).ToString(), 1));
- Console.WriteLine(ToString(i => (i + 1).ToString(), 2));
- Console.WriteLine(ToString(i => (i + 2).ToString(), 3));
- Console.WriteLine(ToString(i => (i + 2).ToString(), 4));
- }
- private static int GetExpressionHash<T>(Expression<Func<T, string>> expression)
- {
- int hash = expression.Body.ToString().GetHashCode();
- // if you consider parameter unimportant - comment this line
- // using quite simple and error-prone hash function h = h * 31 + update
- // you might want to switch to md5 or sha in production
- expression.Parameters.ToList().ForEach(param => hash = hash * 31 + param.Name.GetHashCode());
- return hash;
- }
- private static string ToString<T>(Expression<Func<T, string>> expression, T input)
- {
- var cacheKey = GetExpressionHash(expression);
- if (!_cache.ContainsKey(cacheKey))
- {
- _cache[cacheKey] = expression.Compile();
- Console.WriteLine(String.Format("Compiling expression {0}", expression.ToString()));
- }
- var method = (Func<T, string>) _cache[cacheKey];
- return method.Invoke(input);
- }
- static void Main(string[] args)
- {
- SomeToStringCalls();
- Console.ReadLine();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement