using System;
using System.Linq;
using System.Linq.Expressions;
public class Test
{
private class A
{
private readonly int _value;
public A(int value)
{
_value = value;
}
public int Value { get { return _value; } }
}
private class B
{
private readonly int _value;
private B(int value)
{
_value = value;
}
public int Value { get { return _value; } }
public static explicit operator B(A value)
{
return new B(value.Value);
}
}
private static B ConvertFromObject(object a) {
if (a == null) return null;
var p = Expression.Parameter(typeof(object));
var c1 = Expression.Convert(p, a.GetType());
var c2 = Expression.Convert(c1, typeof(B));
var e = (Func<object,B>)Expression.Lambda(c2, p).Compile();
return e(a);
}
public static void Main()
{
object a = new A(5);
var b = ConvertFromObject(a);
Console.WriteLine("{0}", b.Value);
}
}
dXNpbmcgU3lzdGVtOwp1c2luZyBTeXN0ZW0uTGlucTsKdXNpbmcgU3lzdGVtLkxpbnEuRXhwcmVzc2lvbnM7CgpwdWJsaWMgY2xhc3MgVGVzdAp7CgkKCXByaXZhdGUgY2xhc3MgQQp7CiAgICBwcml2YXRlIHJlYWRvbmx5IGludCBfdmFsdWU7CgogICAgcHVibGljIEEoaW50IHZhbHVlKQogICAgewogICAgICAgIF92YWx1ZSA9IHZhbHVlOwogICAgfQoKICAgIHB1YmxpYyBpbnQgVmFsdWUgeyBnZXQgeyByZXR1cm4gX3ZhbHVlOyB9IH0KfQoKcHJpdmF0ZSBjbGFzcyBCCnsKICAgIHByaXZhdGUgcmVhZG9ubHkgaW50IF92YWx1ZTsKCiAgICBwcml2YXRlIEIoaW50IHZhbHVlKQogICAgewogICAgICAgIF92YWx1ZSA9IHZhbHVlOwogICAgfQoKICAgIHB1YmxpYyBpbnQgVmFsdWUgeyBnZXQgeyByZXR1cm4gX3ZhbHVlOyB9IH0KCiAgICBwdWJsaWMgc3RhdGljIGV4cGxpY2l0IG9wZXJhdG9yIEIoQSB2YWx1ZSkKICAgIHsKICAgICAgICByZXR1cm4gbmV3IEIodmFsdWUuVmFsdWUpOwogICAgfQp9Cglwcml2YXRlIHN0YXRpYyBCIENvbnZlcnRGcm9tT2JqZWN0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