private static bool IsNumericPromotion(Type leftType, Type rightType) {
            if (!leftType.IsNumeric() || !rightType.IsNumeric() || leftType.Equals(TypeSystem.Boolean)) {
                return false;
            }

            return true;
        }
        private static bool IsNumericPromotion(Type type, UnaryOperatorType @operator) {
            if (!type.IsNumeric() ||
                type.Equals(TypeSystem.Boolean) ||
                Array.IndexOf(_unaryOperators, @operator) == -1) {
                return false;
            }

            return true;
        }
 public static IJsonObject BuildJsonObject(Type type, object instance)
 {
     if (type.IsNumeric()) {
         return new NumericJsonProperty(instance);
     }
     if (type == typeof (string)) {
         return new StringJsonProperty(instance);
     }
     if (type.GetInterface("IEnumerable") != null) {
         return new JsonArray((IEnumerable)instance);
     }
     return new JsonClass(instance);
 }
Exemple #4
0
        /// <summary>
        ///     Gets default value of <paramref name="type" />
        /// </summary>
        public static object GetDefaultValue(this Type type)
        {
            if (type.IsClass)
            {
                return(null);
            }

            if (type.IsNumeric())
            {
                return(Script.Write <object>("Bridge.box(0,type)"));
            }

            return(Activator.CreateInstance(type));
        }
        public static string GetCoarseType(Type type)
        {
            if (type.IsDateTime())
                return "datetime";
            if (type.IsNumeric())
                return "numeric";
            if (type.IsString())
                return "string";
            if (type.IsBool())
                return "bool";
            if (type.IsGuid())
                return "guid";

            return "complex";
        }
Exemple #6
0
 private static string GetODSType(Type type)
 {
     if (type == typeof(DateTime) || type == typeof(DateTime?))
     {
         return OfficeValueTypes.Date;
     }
     if (type == typeof(bool) || type == typeof(bool?))
     {
         return OfficeValueTypes.Boolean;
     }
     if (type.IsNumeric())
     {
         return OfficeValueTypes.Float;
     }
     return OfficeValueTypes.String;
 }
        public static string GetCoarseType(Type type)
        {
            if (type.IsTimeSpan())
                return "timespan";
            if (type.IsDateTime())
                return "datetime";
            if (type.IsNumeric())
                return "numeric";
            if (type.IsString())
                return "string";
            if (type.IsBool())
                return "bool";
            if (type.IsGuid())
                return "guid";

            return "object";
        }
        public static string GetCoarseType(Type type)
        {
            if (type.IsTimeSpan())
                return "timespan";
            if (type.IsDateTime())
                return "datetime";
            if (type.IsNumeric())
                return "numeric";
            if (type.IsString())
                return "string";
            if (type.IsBool())
                return "bool";
            if (type.IsGuid())
                return "guid";

            type = type.IsNullable() ? Nullable.GetUnderlyingType(type) : type;
            return type.Name.ToLowerInvariant();
        }
Exemple #9
0
        /// <summary>
        /// Convert the string representation to the destination type
        /// </summary>
        /// <param name="input">Input string</param>
        /// <param name="destinationType">Destination type</param>
        /// <param name="context">Current context</param>
        /// <returns>Converted object of the destination type</returns>
        public object Convert(string input, Type destinationType, BindingContext context)
        {
            var converter = TypeDescriptor.GetConverter(destinationType);

            if (!converter.CanConvertFrom(typeof(string)) || (destinationType.IsNumeric() && string.IsNullOrEmpty(input)))
            {
                return null;
            }

            try
            {
                return converter.ConvertFrom(input);
            }
            catch (FormatException)
            {
                if (destinationType == typeof(bool) && converter.GetType() == typeof(BooleanConverter) && "on".Equals(input, StringComparison.OrdinalIgnoreCase))
                {
                    return true;
                }
                return null;
            }
        }
Exemple #10
0
 /// <summary>
 /// 写入类型转换的 IL 指令。
 /// </summary>
 /// <param name="generator">IL 的指令生成器。</param>
 /// <param name="inputType">要转换的对象的类型。</param>
 /// <param name="outputType">要将输入对象转换到的类型。</param>
 /// <param name="isChecked">是否执行溢出检查。</param>
 public override void Emit(ILGenerator generator, Type inputType, Type outputType, bool isChecked)
 {
     Contract.Assume((inputType == typeof(decimal) && outputType.IsNumeric()) ||
         (outputType == typeof(decimal) && inputType.IsNumeric()));
     MethodInfo method;
     if (inputType == typeof(decimal))
     {
         if (outputType.IsEnum)
         {
             outputType = Enum.GetUnderlyingType(outputType);
         }
         method = UserConversionCache.GetConversionTo(inputType, outputType);
     }
     else
     {
         if (inputType.IsEnum)
         {
             inputType = Enum.GetUnderlyingType(inputType);
         }
         method = UserConversionCache.GetConversionFrom(outputType, inputType);
     }
     generator.EmitCall(method);
 }
        private bool TypesArePrimitiveAndConvertible(Type source, Type dest) {
            Type nonNullableSourceType = source.GetNonNullableType();
            Type nonNullableDestinationType = dest.GetNonNullableType();

            return (!(source.IsEnum || dest.IsEnum)) && (source.IsEquivalentTo(dest) || ((source.IsNullableType() && dest.IsEquivalentTo(nonNullableSourceType)) || ((dest.IsNullableType() && source.IsEquivalentTo(nonNullableDestinationType)) ||
                   ((source.IsNumeric() && dest.IsNumeric()) && (nonNullableDestinationType != TypeSystem.Boolean)))));
        }
Exemple #12
0
 /// <summary>
 /// Whether the converter can convert to the destination type
 /// </summary>
 /// <param name="destinationType">Destination type</param>
 /// <param name="context">The current binding context</param>
 /// <returns>True if conversion supported, false otherwise</returns>
 public bool CanConvertTo(Type destinationType, BindingContext context)
 {
     return destinationType.IsNumeric();
 }
Exemple #13
0
        internal bool TryChangeType(ref object value, Type type)
        {
            if (type != null && type != typeof(object))
            {
                // handle nullable types
                if (type.IsNullableType())
                {
                    // if value is null, we're done
                    if (value == null || object.Equals(value, string.Empty))
                    {
                        value = null;
                        return true;
                    }

                    // get actual type for parsing
                    type = Nullable.GetUnderlyingType(type);
                }
                else if (type.GetTypeInfo().IsValueType && value == null)
                {
                    // not nullable, can't assign null value to this
                    return false;
                }

                // handle special numeric formatting
                var ci = GetCultureInfo();
                var str = value as string;
                if (!string.IsNullOrEmpty(str) && type.IsNumeric())
                {
                    // handle percentages (ci.NumberFormat.PercentSymbol? overkill...)
                    bool pct = str[0] == '%' || str[str.Length - 1] == '%';
                    if (pct)
                    {
                        str = str.Trim('%');
                    }
                    decimal d;
                    if (decimal.TryParse(str, NumberStyles.Any, ci, out d))
                    {
                        if (pct)
                        {
                            value = d / 100;
                        }
                        else
                        {
                            // <<IP>> for currencies Convert.ChangeType will always give exception if we do without parsing,
                            // so change value here to the parsed one
                            value = d;
                        }
                    }
                    else
                    {
                        return false;
                    }
                }

                // ready to change type
                try
                {
                    value = Convert.ChangeType(value, type, ci);
                }
                catch
                {
                    return false;
                }
            }
            return true;
        }
 public override bool CanMatchType(Type requestedType)
 {
     return requestedType == null || requestedType.IsNumeric() || requestedType.GetTypeCode() == TypeCode.Boolean;
 }
Exemple #15
0
		/// <summary>
		/// Creates a field that will contain a value of a specific type
		/// <para xml:lang="es">
		/// Crea un campo que contendra un valor de un tipo especifico.
		/// </para>
		/// </summary>
		public static FormField CreateFieldFrom(Type type)
		{
			//validate arguments
			if (type == null) throw new ArgumentNullException("type");

			//field
			FormField field;

			//Enum
			if (type.GetTypeInfo().IsEnum)
			{
				field = new EnumField(type);
			}

			//Type, ignore this since we can't know if type means Person (as in a serializable object) or typeof(Person) as a type which child types you would choose from
			//else if (type.Equals(typeof(Type)))
			//{
			//	field = new TypeField();
			//}

			//Bool
			else if (type.Equals(typeof(bool)))
			{
				field = new BoolField();
			}

			//DateTime
			else if (type.Equals(typeof(DateTime)))
			{
				field = new DateTimeField();
			}

			//Numeric
			else if (type.IsNumeric())
			{
				if (type.IsIntegral())
				{
					field = new IntegerField();
				}
				else
				{
					field = new DecimalField();
				}
			}

			//String serializable
			else if (type.GetTypeInfo().ImplementedInterfaces.Contains(typeof(Data.IStringSerializable)))
			{
				field = new StringSerializableField(type);
			}

			//XML
			else if (type.GetTypeInfo().ImplementedInterfaces.Contains(typeof(System.Xml.Serialization.IXmlSerializable)))
			{
				field = new XmlSerializableField(type);
			}

			//String
			else if (type.Equals(typeof(string)))
			{
				field = new StringField();
			}

			//byte[]
			else if (type.Equals(typeof(byte[])))
			{
				field = new BinaryField();
			}

			//otherwise just create a textbox
			else
			{
				field = new StringField();
			}

			//return
			return field;
		}
Exemple #16
0
 /// <summary>
 /// 返回从值类型转换为值类型的类型转换。
 /// </summary>
 /// <param name="inputType">要转换的对象的类型。</param>
 /// <param name="outputType">要将输入对象转换到的类型。</param>
 /// <returns>从值类型转换为值类型的类型转换,如果不存在则为 <c>null</c>。</returns>
 private static Conversion GetBetweenValueTypeConversion(Type inputType, Type outputType)
 {
     Contract.Requires(inputType != null && outputType != null);
     Contract.Requires(inputType.IsValueType && outputType.IsValueType);
     TypeCode inputTypeCode = Type.GetTypeCode(inputType);
     TypeCode outputTypeCode = Type.GetTypeCode(outputType);
     // 数值或枚举转换。
     if (inputTypeCode.IsNumeric() && outputTypeCode.IsNumeric())
     {
         return GetNumericOrEnumConversion(inputType, inputTypeCode, outputType, outputTypeCode);
     }
     // 可空类型转换。
     Type inputUnderlyingType = Nullable.GetUnderlyingType(inputType);
     Type outputUnderlyingType = Nullable.GetUnderlyingType(outputType);
     if (inputUnderlyingType != null)
     {
         inputTypeCode = Type.GetTypeCode(inputUnderlyingType);
         if (outputUnderlyingType == null)
         {
             // 可空类型 S? 到非可空值类型 T 的转换。
             // 1. 可空类型为 null,引发异常。
             // 2. 将可空类型解包
             // 3. 执行从 S 到 T 的预定义类型转换。
             // 这里 S 和 T 都是值类型,可能的预定义类型转换只有标识转换和数值转换。
             if (inputUnderlyingType == outputType ||
                 (inputTypeCode.IsNumeric() && outputTypeCode.IsNumeric()))
             {
                 return FromNullableConversion.Default;
             }
             return null;
         }
         outputTypeCode = Type.GetTypeCode(outputUnderlyingType);
         // 可空类型间转换,从 S? 到 T?,与上面同理,但此时不可能有 S==T。
         if (inputTypeCode.IsNumeric() && outputTypeCode.IsNumeric())
         {
             Conversion conversion = GetNumericOrEnumConversion(inputUnderlyingType, inputTypeCode,
                 outputUnderlyingType, outputTypeCode);
             return conversion.ConversionType.IsImplicit()
                 ? BetweenNullableConversion.Implicit : BetweenNullableConversion.Explicit;
         }
         return null;
     }
     if (outputUnderlyingType != null)
     {
         // 非可空类型到可空类型转换,与上面同理。
         if (inputType == outputUnderlyingType)
         {
             return ToNullableConversion.Implicit;
         }
         outputTypeCode = Type.GetTypeCode(outputUnderlyingType);
         if (inputType.IsNumeric() && outputTypeCode.IsNumeric())
         {
             Conversion conversion = GetNumericOrEnumConversion(inputType, inputTypeCode,
                 outputUnderlyingType, outputTypeCode);
             return conversion.ConversionType.IsImplicit() ?
                 ToNullableConversion.Implicit : ToNullableConversion.Explicit;
         }
     }
     return null;
 }
Exemple #17
0
        public void should_deserialize_typed_fields(string suffix, Type type, object value, string name)
        {
            var json = "{{ \"{0}\": {1} }}".ToFormat(name + suffix,
                type.IsNumeric() || type.IsBoolean() ? value.ToString().ToLower() : "\"" + value + "\"");

            var result = Deserialize.Json<SimpleTypeField>(json, x => x.IncludePublicFields());

            result.ShouldNotBeNull();
            result.ShouldBeType<SimpleTypeField>();
            result.GetPropertyOrFieldValue(name + suffix).ShouldEqual(value);
        }
Exemple #18
0
        public void should_serialize_fields(string suffix, Type type, object value, string name)
        {
            var memberName = name + suffix;
            var @object = new SimpleTypeField();
            @object.SetPropertyOrFieldValue(memberName, value);
            var result = Serialize.Json(@object, x => x.IncludePublicFields().IncludeMembersWhen((m, o) => m.Name == memberName));

            var json = "{{\"{0}\":{1}}}".ToFormat(memberName,
                type.IsNumeric() || type.IsBoolean() ?
                    value.ToString().ToLower() :
                    "\"" + value.ToString().Replace("/", "\\/") + "\"");
            result.ShouldEqual(json);
        }
Exemple #19
0
 private object PromptValue(string label, Type type, Collection<Attribute> attributes, string helpMessage)
 {
     if (type == typeof(PSCredential))
     {
         return PromptCredential(label, attributes, helpMessage);
     }
     if (type.IsArray)
     {
         List<object> values = new List<object>();
         while (true)
         {
             var elType = type.GetElementType();
             var val = PromptValue(String.Format("{0}[{1}]", label, values.Count), elType,
                                   attributes, helpMessage);
             if (val == null || (elType == typeof(string) && String.IsNullOrEmpty((string) val)))
             {
                 break;
             }
             values.Add(val);
         }
         return values.ToArray();
     }
     Write(label + ":");
     // TODO: What about EOF here? I guess we'd need to stop the pipeline? Verify this before implementing
     if (type == typeof(System.Security.SecureString))
     {
         return ReadLineAsSecureString();
     }
     string value = ReadLine(false);
     if (value != null && value.Equals("!?"))
     {
         var msg = String.IsNullOrEmpty(helpMessage) ? "No help message provided for " + label : helpMessage;
         WriteLine(msg);
         // simply prompt again
         return PromptValue(label, type, attributes, helpMessage);
     }
     object converted;
     if (!(type.IsNumeric() && String.IsNullOrWhiteSpace(value)) &&
         LanguagePrimitives.TryConvertTo(value, type, out converted))
     {
         // TODO: we should validate the value with the defined Attributes here
         return converted;
     }
     return null;
 }
Exemple #20
0
 internal bool TryChangeType(ref object value, Type type)
 {
     if (type != null && type != typeof (object))
     {
         if (type.IsNullableType())
         {
             if (value == null || Equals(value, string.Empty))
             {
                 value = null;
                 return true;
             }
             type = Nullable.GetUnderlyingType(type);
         }
         else if (type.IsValueType && value == null)
         {
             return false;
         }
         CultureInfo cultureInfo = GetCultureInfo();
         string str = value as string;
         if (!string.IsNullOrEmpty(str) && type.IsNumeric())
         {
             bool startsOrEndsWithPct = str[0] == '%' || str[str.Length - 1] == '%';
             if (startsOrEndsWithPct)
             {
                 str = str.Trim('%');
             }
             decimal d;
             if (!decimal.TryParse(str, NumberStyles.Any, cultureInfo, out d))
             {
                 return false;
             }
             value = !startsOrEndsWithPct ? d : d/100;
         }
         try
         {
             value = Convert.ChangeType(value, type, cultureInfo);
             return true;
         }
         catch
         {
             return false;
         }
     }
     return true;
 }
Exemple #21
0
        public void should_deserialize_string_fields(string suffix, Type type, object value, string name)
        {
            var jsonValue = type.IsNumeric() || type.IsBoolean() ? value.ToString().ToLower() : value;
            var json = $"{{ \"{name + suffix}\": \"{jsonValue}\" }}";

            var result = Deserialize.Json<SimpleTypeField>(json, x => x.IncludePublicFields());

            result.ShouldNotBeNull();
            result.ShouldBeType<SimpleTypeField>();
            result.GetPropertyOrFieldValue(name + suffix).ShouldEqual(value);
        }
Exemple #22
0
        public void Should_deserialize_optional_values(string suffix, Type type, object value, string name)
        {
            var jsonValue = type.IsNumeric() ? value.ToString().ToLower() : "\"" + value + "\"";
            var json = $"{{ \"{name + suffix}\": {jsonValue} }}";

            var result = Deserialize.Json<OptionalValues>(json, x => x.IncludePublicFields());

            var optional = result.GetPropertyOrFieldValue(name + suffix);
            optional.GetPropertyOrFieldValue("HasValue").ShouldEqual(true);
            optional.GetPropertyOrFieldValue("Value").ShouldEqual(value);
        }
 internal static Expression ConvertStringToNumber(Expression expr, Type toType)
 {
     if (!toType.IsNumeric())
     {
         toType = typeof(int);
     }
     return Expression.Call(CachedReflectionInfo.Parser_ScanNumber, expr.Cast(typeof(string)), Expression.Constant(toType));
 }
 public void IsNotNumeric(Type type)
 {
     Assert.False(type.IsNumeric());
 }
 public void IsNumeric(Type type)
 {
     Assert.True(type.IsNumeric());
 }