Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class ConvertTest : ITestable
- {
- private static class TestClass<T> where T : IConvertible
- {
- public static int GetInt(T x)
- {
- return Convert.ToInt32(x);
- }
- public static T GetT(int x)
- {
- return (T)Convert.ChangeType(x, typeof(T));
- }
- }
- }
- class ExpressionTreeTest : ITestable
- {
- private static class TestClass<T> where T : IConvertible
- {
- static Func<T, int> _getInt;
- static Func<int, T> _getT;
- static TestClass()
- {
- var param = Expression.Parameter(typeof(int), "x");
- UnaryExpression body = Expression.Convert(param, typeof(T));
- _getT = Expression.Lambda<Func<int, T>>(body, param).Compile();
- param = Expression.Parameter(typeof(T), "x");
- body = Expression.Convert(param, typeof(int));
- _getInt = Expression.Lambda<Func<T, int>>(body, param).Compile();
- }
- public static int GetInt(T x)
- {
- return _getInt(x);
- }
- public static T GetT(int x)
- {
- return _getT(x);
- }
- }
- }
- class IConvertibleTest : ITestable
- {
- private static class TestClass<T> where T : IConvertible
- {
- public static int GetInt(T x)
- {
- return x.ToInt32(null);
- }
- public static T GetT(int x)
- {
- // horrible, isn't it?!
- return (T)((IConvertible)x).ToType(typeof(T), null);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement