Example #1
0
        private void ExtendedConvertToType(Type fromType, Type toType, bool allowExplicit)
        {
            try
            {
                // See whether we can find a constructor on target type.

                var constructor = _resolver.ResolveMethodGroup(
                    toType.GetConstructors(_resolver.Options.AccessBindingFlags | BindingFlags.CreateInstance),
                    new[] { fromType },
                    new[] { false }
                    );

                if (constructor != null)
                {
                    ILUtil.EmitNew(_il, (ConstructorInfo)constructor);

                    return;
                }

                // See whether we have an implicit cast.

                var castMethod = _resolver.FindOperatorMethod(
                    "op_Implicit",
                    new[] { fromType, toType },
                    toType,
                    new[] { fromType }
                    );

                if (castMethod == null && allowExplicit)
                {
                    castMethod = _resolver.FindOperatorMethod(
                        "op_Explicit",
                        new[] { fromType, toType },
                        toType,
                        new[] { fromType }
                        );
                }

                if (castMethod != null)
                {
                    var parameterType = castMethod.GetParameters()[0].ParameterType;

                    if (fromType != parameterType)
                    {
                        ILUtil.EmitConvertToType(_il, fromType, parameterType, _resolver.Options.Checked);
                    }

                    _il.Emit(OpCodes.Call, castMethod);

                    if (toType != castMethod.ReturnType)
                    {
                        ILUtil.EmitConvertToType(_il, castMethod.ReturnType, toType, _resolver.Options.Checked);
                    }

                    return;
                }

                // Let ILUtill handle it.

                ILUtil.EmitConvertToType(_il, fromType, toType, _resolver.Options.Checked);
            }
            catch (Exception ex)
            {
                throw new ExpressionsException(
                          "Invalid explicit cast",
                          ExpressionsExceptionType.InvalidExplicitCast,
                          ex
                          );
            }
        }