当前位置: 首页>>代码示例>>C#>>正文


C# Type.IsNumericType方法代码示例

本文整理汇总了C#中System.Type.IsNumericType方法的典型用法代码示例。如果您正苦于以下问题:C# Type.IsNumericType方法的具体用法?C# Type.IsNumericType怎么用?C# Type.IsNumericType使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Type的用法示例。


在下文中一共展示了Type.IsNumericType方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ToCode

		private static string ToCode(object val, Type targetType)
		{
			if (val == null)
				return "null";
				
			if (val.Equals(CsDb.CodeGen.Statics.DateTimeNowFunction))
				return $"\"DateTime.Now\"";
			if (val.Equals(CsDb.CodeGen.Statics.NewGuidFunction))
				return $"\"Guid.NewGuid()\"";

			if (targetType == typeof (string))
				return $"\"{val}\"";
			if (targetType == typeof (DateTime))
				return $"\"{val}\"";
			if (targetType == typeof (TimeSpan))
				return $"\"{((TimeSpan)val).ToString("hh\\:mm\\:ss")}\"";
			if (targetType == typeof (bool))
				return $"{val.ToString().ToLower()}";
			if (targetType == typeof (Guid))
				return $"\"{val}\"";
			if (targetType.IsNumericType())
				return val.ToString();

			throw new NotImplementedException("Type is not implemented");
		}
开发者ID:cssack,项目名称:CsGlobals,代码行数:25,代码来源:CsDbDataColumnAttribute.cs

示例2: ConvertUsingTypeConverter

        /// <summary>
        /// Converts a value to the specified type using a <see cref="TypeConverter"/>, if one is available.
        /// </summary>
        /// <param name="value">The value to convert.</param>
        /// <param name="originalType">The value's original type.</param>
        /// <param name="conversionType">The type to which to convert the value.</param>
        /// <returns>The converted value.</returns>
        private static Object ConvertUsingTypeConverter(Object value, Type originalType, Type conversionType)
        {
            var converter = TypeDescriptor.GetConverter(conversionType);
            if (converter != null && converter.CanConvertFrom(originalType))
            {
                /* HACK: converter.IsValid() will throw an exception for null/empty strings
                 * in some circumstances. It's handled in System.dll but ultimately a pointless
                 * inefficiency, so we prevent that here. */
                var assumeInvalid = false;
                if (originalType == typeof(String) && conversionType.IsNumericType())
                {
                    if (String.IsNullOrEmpty((String)value))
                        assumeInvalid = true;
                }

                if (!assumeInvalid && converter.IsValid(value))
                {
                    return converter.ConvertFrom(value);
                }
            }

            if (conversionType.IsAssignableFrom(originalType))
                return value;

            return conversionType.IsClass ? null : Activator.CreateInstance(conversionType);
        }
开发者ID:prshreshtha,项目名称:ultraviolet,代码行数:33,代码来源:BindingConversions.cs

示例3: Resolve

        public override IEnumerable<PatternNameBinding> Resolve(Context ctx, Type expressionType)
        {
            var startType = RangeStartRule.Literal.LiteralType;
            var endType = RangeEndRule.Literal.LiteralType;

            if(!startType.IsNumericType() || !endType.IsNumericType())
                Error(CompilerMessages.PatternRangeNotNumeric);

            if(!expressionType.IsNumericType())
                Error(CompilerMessages.PatternTypeMismatch, expressionType, "int");

            return NoBindings();
        }
开发者ID:menozz,项目名称:lens,代码行数:13,代码来源:MatchRangeRule.cs

示例4: TypeIsSelfBindable

 // All other types should attempt to do a resolution via self binding.
 protected override bool TypeIsSelfBindable(Type service)
 {
     return !service.IsInterface
         && !service.IsAbstract
         && !service.ContainsGenericParameters
         && !service.IsEnum
         && !service.IsArray
         && !service.IsNumericType()
         && !service.IsString()
         && !service.IsBoolean()
         && !service.IsDateTime()
         && service != typeof(char);
 }
开发者ID:harshtandon,项目名称:InstanceLocator,代码行数:14,代码来源:CustomSelfBindingResolver.cs

示例5: ToQuotedString

        public override string ToQuotedString(Type fieldType, object value)
        {
            var isEnumFlags = fieldType.IsEnumFlags() ||
                (!fieldType.IsEnum && fieldType.IsNumericType()); //i.e. is real int && not Enum

            long enumValue;
            if (!isEnumFlags && long.TryParse(value.ToString(), out enumValue))
                value = Enum.ToObject(fieldType, enumValue);

            var enumString = DialectProvider.StringSerializer.SerializeToString(value);
            if (enumString == null || enumString == "null")
                enumString = value.ToString();

            return !isEnumFlags 
                ? DialectProvider.GetQuotedValue(enumString.Trim('"')) 
                : enumString;
        }
开发者ID:wrx362114,项目名称:ServiceStack.OrmLite,代码行数:17,代码来源:SpecialConverters.cs

示例6: ToQuotedString

        public override string ToQuotedString(Type fieldType, object value)
        {
            var isEnumAsInt = fieldType.HasAttribute<EnumAsIntAttribute>();
            if (isEnumAsInt)
                return this.ConvertNumber(Enum.GetUnderlyingType(fieldType), value).ToString();

            var isEnumFlags = fieldType.IsEnumFlags() ||
                (!fieldType.IsEnum() && fieldType.IsNumericType()); //i.e. is real int && not Enum

            long enumValue;
            if (!isEnumFlags && long.TryParse(value.ToString(), out enumValue))
                value = Enum.ToObject(fieldType, enumValue);

            var enumString = DialectProvider.StringSerializer.SerializeToString(value);
            if (enumString == null || enumString == "null")
                enumString = value.ToString();

            return !isEnumFlags 
                ? DialectProvider.GetQuotedValue(enumString.Trim('"')) 
                : enumString;
        }
开发者ID:ServiceStack,项目名称:ServiceStack.OrmLite,代码行数:21,代码来源:SpecialConverters.cs

示例7: ToDbValue

        public override object ToDbValue(Type fieldType, object value)
        {
            var isEnumFlags = fieldType.IsEnumFlags() ||
                (!fieldType.IsEnum && fieldType.IsNumericType()); //i.e. is real int && not Enum

            if (isEnumFlags && value.GetType().IsEnum)
                return Convert.ChangeType(value, fieldType.GetTypeCode());

            long enumValue;
            if (long.TryParse(value.ToString(), out enumValue))
            {
                if (isEnumFlags)
                    return enumValue;

                value = Enum.ToObject(fieldType, enumValue);
            }

            var enumString = DialectProvider.StringSerializer.SerializeToString(value);
            return enumString != null && enumString != "null"
                ? enumString.Trim('"') 
                : value.ToString();
        }
开发者ID:wrx362114,项目名称:ServiceStack.OrmLite,代码行数:22,代码来源:SpecialConverters.cs

示例8: GetDafaultValueCode

		private static string GetDafaultValueCode(object def, Type targetType)
		{
			if (def.Equals(CsDb.CodeGen.Statics.DateTimeNowFunction))
				return "DateTime.Now";
			if (def.Equals(CsDb.CodeGen.Statics.NewGuidFunction))
				return "Guid.NewGuid()";



			if (targetType.IsNumericType())
				return def.ToString();
			if (targetType == typeof (DateTime))
				return $"new DateTime({((DateTime) def).Ticks})";
			if (targetType == typeof (TimeSpan))
				return $"new TimeSpan({((TimeSpan) def).Ticks})";
			if (targetType == typeof (bool))
				return def.ToString().ToLower();
			if (targetType == typeof (string))
				return $"\"{def}\"";



			throw new Exception("Unknown data format");
		}
开发者ID:cssack,项目名称:CsGlobals,代码行数:24,代码来源:CsDbcTableRow_ApplyDefaults.cs

示例9: WidenNumeric

        private static void WidenNumeric(ref Object value, ref Type valueType)
        {
            if (!valueType.IsNumericType() ||
                (valueType == typeof(Double)))
                return;

            value = TypeHelper.Convert<Double>(value);
            valueType = typeof(Double);
        }
开发者ID:richardhopton,项目名称:Flux,代码行数:9,代码来源:ComparisonCondition.cs

示例10: distanceFrom

        private static int distanceFrom(Type varType, Type exprType, bool exactly = false)
        {
            if (varType == exprType)
                return 0;

            if (varType.IsByRef)
                return varType.GetElementType() == exprType ? 0 : int.MaxValue;

            if (!exactly)
            {
                if (varType.IsNullableType() && exprType == Nullable.GetUnderlyingType(varType))
                    return 1;

                if ((varType.IsClass || varType.IsNullableType()) && exprType == typeof (NullType))
                    return 1;

                if (varType.IsNumericType() && exprType.IsNumericType())
                    return NumericTypeConversion(varType, exprType);
            }

            if (varType == typeof (object))
            {
                if (exprType.IsValueType)
                    return exactly ? int.MaxValue : 1;

                if (exprType.IsInterface)
                    return 1;
            }

            if (varType.IsInterface)
            {
                if (exprType.IsInterface)
                    return InterfaceDistance(varType, new[] { exprType }.Union(GenericHelper.GetInterfaces(exprType)));

                // casting expression to interface takes 1 step
                var dist = InterfaceDistance(varType, GenericHelper.GetInterfaces(exprType));
                if (dist < int.MaxValue)
                    return dist + 1;
            }

            if (varType.IsGenericParameter || exprType.IsGenericParameter)
                return GenericParameterDistance(varType, exprType);

            if (varType.IsGenericType && exprType.IsGenericType)
                return GenericDistance(varType, exprType);

            int result;
            if (IsDerivedFrom(exprType, varType, out result))
                return result;

            if (varType.IsArray && exprType.IsArray)
            {
                var varElType = varType.GetElementType();
                var exprElType = exprType.GetElementType();

                var areRefs = !varElType.IsValueType && !exprElType.IsValueType;
                var generic = varElType.IsGenericParameter || exprElType.IsGenericParameter;
                if(areRefs || generic)
                    return varElType.DistanceFrom(exprElType, exactly);
            }

            return int.MaxValue;
        }
开发者ID:TrickyCat,项目名称:lens,代码行数:63,代码来源:TypeExtensions.cs

示例11: AddTypeOptions

 private void AddTypeOptions(Dictionary<string, object> options, Type type)
 {
     if (type.IsNumericType())
     {
         options["type"] = type.Name.ToLower();
     }
     else if (Nullable.GetUnderlyingType(type)?.IsNumericType() == true)
     {
         options["type"] = Nullable.GetUnderlyingType(type).Name.ToLower() + "?";
     }
 }
开发者ID:darilek,项目名称:dotvvm,代码行数:11,代码来源:ViewModelSerializationMap.cs

示例12: ToDefaultValue

			private static object ToDefaultValue(string defaultValue, Type dotNetType)
			{
				if (defaultValue == null)
					return null;


				if (dotNetType.IsNumericType())
					return Convert.ChangeType(defaultValue.Trim('(', ')'), dotNetType);


				if (dotNetType == typeof (DateTime))
				{
					if (defaultValue.ToLower() == "(getdate())")
						return CsDb.CodeGen.Statics.DateTimeNowFunction;
					return Convert.ToDateTime(defaultValue.Trim('(', ')', '\''));
				}
				if (dotNetType == typeof (TimeSpan))
				{
					return TimeSpan.Parse(defaultValue.Trim('(', ')', '\''));
				}
				if (dotNetType == typeof (Guid))
				{
					if (defaultValue.ToLower() == "(newid())")
						return CsDb.CodeGen.Statics.NewGuidFunction;
					throw new InvalidOperationException("Unknown Default value found. Include a conversion to a valid C# instance. If it is a function please use the 'CsDb.CodeGen.Statics' name space to set the value to a string.");
				}
				if (dotNetType == typeof (string))
				{
					var lower = defaultValue.ToLower();
					if (lower == "(null)")
						return null;
					if (lower.StartsWith("('") && lower.EndsWith("')"))
						return defaultValue.Substring(2, defaultValue.Length - 4);
					if (lower.StartsWith("(n'") && lower.EndsWith("')"))
						return defaultValue.Substring(3, defaultValue.Length - 5);
					throw new InvalidOperationException("Unknown Default value found. Include a conversion to a valid C# instance. If it is a function please use the 'CsDb.CodeGen.Statics' name space to set the value to a string.");
				}
				if (dotNetType == typeof (bool))
				{
					if (defaultValue.ToLower() == "((0))")
						return false;
					if (defaultValue.ToLower() == "((1))")
						return true;
				}


				// Include a conversion to a valid C# instance.
				// If it is a function please use the 'CsDb.CodeGen.Statics' name space
				// Other exception in code generation will follow. Use description there to include conversion logic.

				throw new InvalidOperationException("Unknown Default value found. Include a conversion to a valid C# instance. If it is a function please use the 'CsDb.CodeGen.Statics' name space to set the value to a string.");
			}
开发者ID:cssack,项目名称:CsGlobals,代码行数:52,代码来源:CsDbArcGen_Sql.cs

示例13: canCompare

        /// <summary>
        /// Checks if two types can be compared.
        /// </summary>
        private bool canCompare(Type left, Type right, bool equalityOnly)
        {
            // there's an overridden method
            if (m_OverloadedMethod != null)
                return true;

            // string .. string
            if (left == typeof(string) && right == left)
                return true;

            // numeric .. numeric
            if (left.IsNumericType() && right.IsNumericType())
                return left.IsUnsignedIntegerType() == right.IsUnsignedIntegerType();

            if (equalityOnly)
            {
                // Nullable<T> .. (Nullable<T> | T | null)
                if (left.IsNullableType())
                    return left == right || Nullable.GetUnderlyingType(left) == right || right == typeof (NullType);

                if (right.IsNullableType())
                    return Nullable.GetUnderlyingType(right) == left || left == typeof (NullType);

                // ref type .. null
                if ((right == typeof (NullType) && !left.IsValueType) || (left == typeof (NullType) && !right.IsValueType))
                    return true;

                if (left is TypeBuilder && left == right)
                    return true;

            }

            return false;
        }
开发者ID:TrickyCat,项目名称:lens,代码行数:37,代码来源:ComparisonOperatorNode.cs

示例14: compileEquality

        /// <summary>
        /// Emits code for equality and inequality comparison.
        /// </summary>
        private void compileEquality(Context ctx, Type left, Type right)
        {
            var gen = ctx.CurrentILGenerator;

            // compare two strings
            if (left == typeof (string) && right == typeof (string))
            {
                LeftOperand.Compile(ctx, true);
                RightOperand.Compile(ctx, true);

                var method = typeof (string).GetMethod("Equals", new[] {typeof (string), typeof (string)});
                gen.EmitCall(method);

                if (Kind == ComparisonOperatorKind.NotEquals)
                    emitInversion(gen);

                return;
            }

            // compare two numerics
            if (left.IsNumericType() && right.IsNumericType())
            {
                loadAndConvertNumerics(ctx);
                gen.EmitCompareEqual();

                if(Kind == ComparisonOperatorKind.NotEquals)
                    emitInversion(gen);

                return;
            }

            // compare nullable against another nullable, it's base type or null
            if (left.IsNullableType())
            {
                if(left == right || Nullable.GetUnderlyingType(left) == right)
                    compileNullable(ctx, LeftOperand, RightOperand);
                else if(right == typeof(NullType))
                    compileHasValue(ctx, LeftOperand);

                return;
            }

            if (right.IsNullableType())
            {
                if (Nullable.GetUnderlyingType(right) == left)
                    compileNullable(ctx, RightOperand, LeftOperand);
                else if (left == typeof(NullType))
                    compileHasValue(ctx, RightOperand);

                return;
            }

            // compare a reftype against a null
            if (left == typeof(NullType) || right == typeof(NullType))
            {
                LeftOperand.Compile(ctx, true);
                RightOperand.Compile(ctx, true);
                gen.EmitCompareEqual();

                if (Kind == ComparisonOperatorKind.NotEquals)
                    emitInversion(gen);

                return;
            }

            if (left is TypeBuilder && left == right)
            {
                var equals = ctx.ResolveMethod(left, "Equals", new [] { typeof (object) });

                LeftOperand.Compile(ctx, true);
                RightOperand.Compile(ctx, true);

                gen.EmitCall(equals.MethodInfo);

                if (Kind == ComparisonOperatorKind.NotEquals)
                    emitInversion(gen);

                return;
            }
        }
开发者ID:TrickyCat,项目名称:lens,代码行数:83,代码来源:ComparisonOperatorNode.cs

示例15: emitEqualityComparison

        /// <summary>
        /// Emits code for equality and inequality comparison.
        /// </summary>
        private void emitEqualityComparison(Context ctx, Type left, Type right)
        {
            var gen = ctx.CurrentMethod.Generator;

            // compare two strings
            if (left == right && left == typeof (string))
            {
                LeftOperand.Emit(ctx, true);
                RightOperand.Emit(ctx, true);

                var method = typeof (string).GetMethod("Equals", new[] {typeof (string), typeof (string)});
                gen.EmitCall(method);

                if (Kind == ComparisonOperatorKind.NotEquals)
                    emitInversion(gen);

                return;
            }

            // compare primitive types
            if ((left.IsNumericType() && right.IsNumericType()) || (left == right && left == typeof(bool)))
            {
                if (left == typeof (bool))
                {
                    LeftOperand.Emit(ctx, true);
                    RightOperand.Emit(ctx, true);
                }
                else
                {
                    loadAndConvertNumerics(ctx);
                }

                gen.EmitCompareEqual();

                if(Kind == ComparisonOperatorKind.NotEquals)
                    emitInversion(gen);

                return;
            }

            // compare nullable against another nullable, it's base type or null
            if (left.IsNullableType())
            {
                if(left == right || Nullable.GetUnderlyingType(left) == right)
                    emitNullableComparison(ctx, LeftOperand, RightOperand);
                else if(right == typeof(NullType))
                    emitHasValueCheck(ctx, LeftOperand);

                return;
            }

            if (right.IsNullableType())
            {
                if (Nullable.GetUnderlyingType(right) == left)
                    emitNullableComparison(ctx, RightOperand, LeftOperand);
                else if (left == typeof(NullType))
                    emitHasValueCheck(ctx, RightOperand);

                return;
            }

            // compare a reftype against a null
            if (left == typeof(NullType) || right == typeof(NullType))
            {
                LeftOperand.Emit(ctx, true);
                RightOperand.Emit(ctx, true);
                gen.EmitCompareEqual();

                if (Kind == ComparisonOperatorKind.NotEquals)
                    emitInversion(gen);

                return;
            }

            if (left is TypeBuilder && left == right)
            {
                var equals = ctx.ResolveMethod(left, "Equals", new [] { typeof (object) });

                LeftOperand.Emit(ctx, true);
                RightOperand.Emit(ctx, true);

                gen.EmitCall(equals.MethodInfo);

                if (Kind == ComparisonOperatorKind.NotEquals)
                    emitInversion(gen);

                return;
            }

            throw new ArgumentException("Unknown types to compare!");
        }
开发者ID:menozz,项目名称:lens,代码行数:94,代码来源:ComparisonOperatorNode.cs


注:本文中的System.Type.IsNumericType方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。