コード例 #1
0
        private static void AttemptImplicitCast <TFrom, TTo>()
        {
            // based on the IL produced by:
            // dynamic list = new List<TTo>();
            // list.Add(Get<TFrom>());
            // We can't use the above code because it will mimic a cast in a generic method
            // which doesn't have the same semantics as a cast in a non-generic method

            var list   = new List <TTo>(capacity: 0);
            var binder = CSharpBinder.InvokeMember(
                flags: CSharpBinderFlags.ResultDiscarded,
                name: "Add",
                typeArguments: null,
                context: typeof(Helpers),
                argumentInfo: new[]
            {
                CSharpArgumentInfo.Create(flags: CSharpArgumentInfoFlags.None, name: null),
                CSharpArgumentInfo.Create(
                    flags: CSharpArgumentInfoFlags.UseCompileTimeType,
                    name: null
                    ),
            }
                );
            var callSite = CallSite <Action <CallSite, object, TFrom> > .Create(binder);

            callSite.Target.Invoke(callSite, list, default(TFrom));
        }
コード例 #2
0
        private static void AttemptExplicitCast <TFrom, TTo>()
        {
            // based on the IL generated from
            // var x = (TTo)(dynamic)default(TFrom);

            var binder   = CSharpBinder.Convert(CSharpBinderFlags.ConvertExplicit, typeof(TTo), typeof(ConversionHelpers));
            var callSite = CallSite <Func <CallSite, TFrom, TTo> > .Create(binder);

            callSite.Target(callSite, default(TFrom));
        }