Beispiel #1
0
        /// <summary>
        /// Converts any JavaScript value to a primitive string value.
        /// </summary>
        /// <param name="value"> The value to convert. </param>
        /// <returns> A primitive string value. </returns>
        public static string ToString(object value)
        {
            if (value == null || value == Undefined.Value)
            {
                return("undefined");
            }
            if (value == Null.Value)
            {
                return("null");
            }
            if (value is bool)
            {
                return((bool)value ? "true" : "false");
            }
            if (value is int)
            {
                return(((int)value).ToString());
            }
            if (value is uint)
            {
                return(((uint)value).ToString());
            }
            if (value is double)
            {
                // Check if the value is in the cache.
                double doubleValue = (double)value;
                var    cache       = numberToStringCache;
                if (doubleValue == cache.Value)
                {
                    return(cache.Result);
                }

                // Convert the number to a string.
                var result = NumberFormatter.ToString((double)value, 10, NumberFormatter.Style.Regular);

                // Cache the result.
                // This is thread-safe on Intel but not architectures with weak write ordering.
                numberToStringCache = new NumberToStringCache()
                {
                    Value = doubleValue, Result = result
                };

                return(result);
            }
            if (value is string)
            {
                return((string)value);
            }
            if (value is ConcatenatedString)
            {
                return(value.ToString());
            }
            if (value is SymbolInstance)
            {
                throw new JavaScriptException(((SymbolInstance)value).Engine, ErrorType.TypeError, "Cannot convert a Symbol value to a string.");
            }
            if (value is ObjectInstance)
            {
                return(ToString(ToPrimitive(value, PrimitiveTypeHint.String)));
            }
            throw new ArgumentException(string.Format("Cannot convert object of type '{0}' to a string.", value.GetType()), nameof(value));
        }