fork download
  1. using System;
  2. using System.Linq;
  3. using System.Linq.Expressions;
  4.  
  5. public class Test
  6. {
  7.  
  8. private class A
  9. {
  10. private readonly int _value;
  11.  
  12. public A(int value)
  13. {
  14. _value = value;
  15. }
  16.  
  17. public int Value { get { return _value; } }
  18. }
  19.  
  20. private class B
  21. {
  22. private readonly int _value;
  23.  
  24. private B(int value)
  25. {
  26. _value = value;
  27. }
  28.  
  29. public int Value { get { return _value; } }
  30.  
  31. public static explicit operator B(A value)
  32. {
  33. return new B(value.Value);
  34. }
  35. }
  36. private static B ConvertFromObject(object a) {
  37. if (a == null) return null;
  38. var p = Expression.Parameter(typeof(object));
  39. var c1 = Expression.Convert(p, a.GetType());
  40. var c2 = Expression.Convert(c1, typeof(B));
  41. var e = (Func<object,B>)Expression.Lambda(c2, p).Compile();
  42. return e(a);
  43. }
  44.  
  45. public static void Main()
  46. {
  47. object a = new A(5);
  48. var b = ConvertFromObject(a);
  49. Console.WriteLine("{0}", b.Value);
  50. }
  51. }
Success #stdin #stdout 0.14s 26168KB
stdin
Standard input is empty
stdout
5