Advertisement
Guest User

mjuraszek-iconvertible-tests

a guest
Aug 15th, 2013
444
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.74 KB | None | 0 0
  1.     class ConvertTest : ITestable
  2.     {
  3.         private static class TestClass<T> where T : IConvertible
  4.         {
  5.             public static int GetInt(T x)
  6.             {
  7.                 return Convert.ToInt32(x);
  8.             }
  9.  
  10.             public static T GetT(int x)
  11.             {
  12.                 return (T)Convert.ChangeType(x, typeof(T));
  13.             }
  14.         }
  15.     }
  16.  
  17.     class ExpressionTreeTest : ITestable
  18.     {
  19.         private static class TestClass<T> where T : IConvertible
  20.         {
  21.             static Func<T, int> _getInt;
  22.             static Func<int, T> _getT;
  23.  
  24.             static TestClass()
  25.             {
  26.                 var param = Expression.Parameter(typeof(int), "x");
  27.                 UnaryExpression body = Expression.Convert(param, typeof(T));
  28.                 _getT = Expression.Lambda<Func<int, T>>(body, param).Compile();
  29.  
  30.                 param = Expression.Parameter(typeof(T), "x");
  31.                 body = Expression.Convert(param, typeof(int));
  32.                 _getInt = Expression.Lambda<Func<T, int>>(body, param).Compile();
  33.             }
  34.  
  35.             public static int GetInt(T x)
  36.             {
  37.                 return _getInt(x);
  38.             }
  39.  
  40.             public static T GetT(int x)
  41.             {
  42.                 return _getT(x);
  43.             }
  44.         }
  45.     }
  46.  
  47.     class IConvertibleTest : ITestable
  48.     {
  49.         private static class TestClass<T> where T : IConvertible
  50.         {
  51.             public static int GetInt(T x)
  52.             {
  53.                 return x.ToInt32(null);
  54.             }
  55.  
  56.             public static T GetT(int x)
  57.             {
  58.                 // horrible, isn't it?!
  59.                 return (T)((IConvertible)x).ToType(typeof(T), null);
  60.             }
  61.         }
  62.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement