Exemplo n.º 1
0
        /// <inheritdoc />
        protected override object ExecuteToken(ScriptContext context)
        {
            string typename = TargetType.Execute(context)?.ToString();

            if (typename == null)
            {
                throw new ScriptRuntimeException("cannot cast to null", this);
            }
            Type type = TypeProvider.DetermineType(this, typename);

            object value = Value.Execute(context);

            if (IsDynamic?.Execute(context)?.ToBoolean() ?? false)
            {
                if (value == null)
                {
                    if (type.IsValueType)
                    {
                        return(Activator.CreateInstance(type));
                    }
                    return(null);
                }

                if (type.IsInstanceOfType(value))
                {
                    return(value);
                }
                return(null);
            }

            if (value == null)
            {
                if (type.IsValueType)
                {
                    throw new ScriptRuntimeException($"null cannot get cast to '{typename}'", this);
                }
                return(null);
            }

            if (!type.IsInstanceOfType(value))
            {
                throw new ScriptRuntimeException($"Unable to cast {value} to '{typename}'", this);
            }

            return(value);
        }