fork download
  1. using System;
  2. using System.Diagnostics;
  3. using System.Linq.Expressions;
  4.  
  5. namespace SampleConsoleApp1
  6. {
  7. static class StaticCast<TSource, TDestination>
  8. {
  9. private static Func<TSource, TDestination> cast = GenerateCast();
  10.  
  11. private static Func<TSource, TDestination> GenerateCast()
  12. {
  13. var param = Expression.Parameter(typeof(TSource));
  14. var convert = Expression.Convert(param, typeof(TDestination));
  15. var lambda = Expression.Lambda<Func<TSource, TDestination>>(convert, param);
  16. return lambda.Compile();
  17. }
  18.  
  19. public static TDestination Apply(TSource value) {
  20. return cast(value);
  21. }
  22. }
  23.  
  24. class NumUpDownEx<T>
  25. {
  26. public decimal m_ud_value;
  27. public T Value
  28. {
  29. get { return StaticCast<decimal, T>.Apply(m_ud_value); }
  30. }
  31. }
  32.  
  33. class Program
  34. {
  35. static void Main(string[] args)
  36. {
  37. var obj1 = new NumUpDownEx<int>();
  38. obj1.m_ud_value = 1234m;
  39. Console.WriteLine(1234 == obj1.Value);
  40. var obj2 = new NumUpDownEx<double>();
  41. obj2.m_ud_value = 3456.7m;
  42. Console.WriteLine((double)3456.7m == obj2.Value);
  43. }
  44. }
  45. }
  46.  
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cs(13,36): error CS1501: No overload for method `Parameter' takes `1' arguments
/usr/lib/mono/gac/System.Core/3.5.0.0__b77a5c561934e089/System.Core.dll (Location of the symbol related to previous error)
prog.cs(14,38): error CS1502: The best overloaded method match for `System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)' has some invalid arguments
/usr/lib/mono/gac/System.Core/3.5.0.0__b77a5c561934e089/System.Core.dll (Location of the symbol related to previous error)
prog.cs(14,38): error CS1503: Argument `#1' cannot convert `object' expression to type `System.Linq.Expressions.Expression'
prog.cs(15,37): error CS1502: The best overloaded method match for `System.Linq.Expressions.Expression.Lambda<System.Func<TSource,TDestination>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])' has some invalid arguments
/usr/lib/mono/gac/System.Core/3.5.0.0__b77a5c561934e089/System.Core.dll (Location of the symbol related to previous error)
prog.cs(15,37): error CS1503: Argument `#1' cannot convert `object' expression to type `System.Linq.Expressions.Expression'
prog.cs(16,27): error CS1061: Type `object' does not contain a definition for `Compile' and no extension method `Compile' of type `object' could be found (are you missing a using directive or an assembly reference?)
Compilation failed: 6 error(s), 0 warnings
stdout
Standard output is empty