System.Type.GetTypeCode(System.Type)

Here are the examples of the csharp api System.Type.GetTypeCode(System.Type) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

846 Examples 7

19 View Source File : EnumExtensions.cs
License : MIT License
Project Creator : aliencube

public static string ToDataType(this Type type)
        {
            var @enum = Type.GetTypeCode(type);
            if (!type.IsNullOrDefault() && type.IsEnum)
            {
                @enum = TypeCode.String;
            }

            switch (@enum)
            {
                case TypeCode.Int16:
                case TypeCode.Int32:
                case TypeCode.Int64:
                    return "integer";

                case TypeCode.Single:
                case TypeCode.Double:
                case TypeCode.Decimal:
                    return "number";

                case TypeCode.Boolean:
                    return "boolean";

                case TypeCode.DateTime:
                case TypeCode.String:
                    return "string";

                case TypeCode.Object:
                    if (type == typeof(Guid))
                    {
                        return "string";
                    }
                    else if (type == typeof(DateTime))
                    {
                        return "string";
                    }
                    else if (type == typeof(DateTimeOffset))
                    {
                        return "string";
                    }
                    else
                    {
                        return "object";
                    }

                case TypeCode.Empty:
                case TypeCode.DBNull:
                case TypeCode.Char:
                case TypeCode.SByte:
                case TypeCode.Byte:
                case TypeCode.UInt16:
                case TypeCode.UInt32:
                case TypeCode.UInt64:
                default:
                    throw new InvalidOperationException("Invalid data type");
            }
        }

19 View Source File : CustomAttributeWriter.cs
License : GNU General Public License v3.0
Project Creator : anydream

static bool ToUInt64(object o, out ulong result) {
			if (o == null) {
				result = 0;
				return false;
			}

			switch (Type.GetTypeCode(o.GetType())) {
			case TypeCode.Boolean:
				result = (bool)o ? 1UL : 0UL;
				return true;

			case TypeCode.Char:
				result = (ushort)(char)o;
				return true;

			case TypeCode.SByte:
				result = (ulong)(sbyte)o;
				return true;

			case TypeCode.Byte:
				result = (byte)o;
				return true;

			case TypeCode.Int16:
				result = (ulong)(short)o;
				return true;

			case TypeCode.UInt16:
				result = (ushort)o;
				return true;

			case TypeCode.Int32:
				result = (ulong)(int)o;
				return true;

			case TypeCode.UInt32:
				result = (uint)o;
				return true;

			case TypeCode.Int64:
				result = (ulong)(long)o;
				return true;

			case TypeCode.UInt64:
				result = (ulong)o;
				return true;

			case TypeCode.Single:
				result = (ulong)(float)o;
				return true;

			case TypeCode.Double:
				result = (ulong)(double)o;
				return true;
			}

			result = 0;
			return false;
		}

19 View Source File : DictionaryExtensions.cs
License : MIT License
Project Creator : actions

public static bool TryGetValidatedValue<T>(this IDictionary<string, object> dictionary, string key, out T value, bool allowNull = true)
        {
            value = default(T);
            //try to convert to T. T *must* be something with
            //TypeCode != TypeCode.object (and not DBNull) OR
            //byte[] or guid or object.
            if (!PropertyValidation.IsValidConvertibleType(typeof(T)))
            {
                return false;
            }

            //special case guid...
            if (typeof(T) == typeof(Guid))
            {
                Guid guidVal;
                if (dictionary.TryGetGuid(key, out guidVal))
                {
                    value = (T)(object)guidVal;
                    return true;
                }
            }
            else
            {
                object objValue = null;
                if (dictionary.TryGetValue(key, out objValue))
                {
                    if (objValue == null)
                    {
                        //we found it and it is
                        //null, which may be okay depending on the allowNull flag
                        //value is already = default(T)
                        return allowNull;
                    }

                    if (typeof(T).GetTypeInfo().IsreplacedignableFrom(objValue.GetType().GetTypeInfo()))
                    {
                        value = (T)objValue;
                        return true;
                    }

                    if (typeof(T).GetTypeInfo().IsEnum)
                    {
                        if (dictionary.TryGetEnum(key, out value))
                        {
                            return true;
                        }
                    }

                    if (objValue is string)
                    {
                        TypeCode typeCode = Type.GetTypeCode(typeof(T));

                        try
                        {
                            value = (T)Convert.ChangeType(objValue, typeCode, CultureInfo.CurrentCulture);
                            return true;
                        }
                        catch (Exception)
                        {
                            return false;
                        }
                    }
                }
            }

            return false;
        }

19 View Source File : TypeHelper.cs
License : MIT License
Project Creator : AlenToma

public static bool IsInteger(Type type)
        {
            Type nnType = GetNonNullableType(type);
            switch (Type.GetTypeCode(nnType))
            {
                case TypeCode.SByte:
                case TypeCode.Int16:
                case TypeCode.Int32:
                case TypeCode.Int64:
                case TypeCode.Byte:
                case TypeCode.UInt16:
                case TypeCode.UInt32:
                case TypeCode.UInt64:
                    return true;
                default:
                    return false;
            }
        }

19 View Source File : Ecall.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

private static object PopObject(DarksVMContext ctx, Type type, ref uint sp)
        {
            var arg = ctx.Stack[sp--];
            if(Type.GetTypeCode(type) == TypeCode.String && arg.O == null)
                return ctx.Instance.Data.LookupString(arg.U4);
            return arg.ToObject(type);
        }

19 View Source File : ConversionHelper.cs
License : MIT License
Project Creator : abdullin

internal static bool TryAdaptToDecimal(object value, [NotNull] Type type, out double result)
		{
			if (value != null)
			{
				switch (Type.GetTypeCode(type))
				{
					case TypeCode.Int16: { result = (short)value; return true; }
					case TypeCode.UInt16: { result = (ushort)value; return true; }
					case TypeCode.Int32: { result = (int)value; return true; }
					case TypeCode.UInt32: { result = (uint)value; return true; }
					case TypeCode.Int64: { result = (long)value; return true; }
					case TypeCode.UInt64: { result = (ulong)value; return true; }
					case TypeCode.Single: { result = (float)value; return true; }
					case TypeCode.Double: { result = (double)value; return true; }
						//TODO: string?
				}
			}
			result = 0;
			return false;
		}

19 View Source File : TypeExtensions.cs
License : MIT License
Project Creator : anet-team

public static TypeCode GetTypeCode(Type type) => Type.GetTypeCode(type);

19 View Source File : TypeFuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz

private T GenerateInstanceOf<T>(int recursionLevel)
        {
            recursionLevel++;
            if (recursionLevel > MaxRecursionAllowedWhileFuzzing)
            {
                return default(T);
            }

            var type = typeof(T);

            var constructor = type.GetConstructorWithBiggestNumberOfParameters();
            if (constructor == null || type.IsCoveredByAFuzzer()) // the case with some BCL types
            {
                var instance = FuzzAnyDotNetType(Type.GetTypeCode(type), type, recursionLevel);
                return (T)instance;
            }

            if (constructor.IsEmpty())
            {
                var instance = InstantiateAndFuzzViaPropertiesWhenTheyHaveSetters<T>(constructor, recursionLevel, type);
                return instance;
            }
            else
            {
                try
                {
                    return InstantiateAndFuzzViaConstructorWithBiggestNumberOfParameters<T>(constructor, recursionLevel);
                }
                catch (Exception)
                {
                    return InstantiateAndFuzzViaOtherConstructorIteratingOnAllThemUntilItWorks<T>(recursionLevel, type);
                }
            }
        }

19 View Source File : CustomAttributeWriter.cs
License : GNU General Public License v3.0
Project Creator : anydream

bool TryWriteEnumUnderlyingTypeValue(object o) {
			if (o == null)
				return false;
			switch (Type.GetTypeCode(o.GetType())) {
			case TypeCode.Boolean:	writer.Write((bool)o); break;
			case TypeCode.Char:		writer.Write((ushort)(char)o); break;
			case TypeCode.SByte:	writer.Write((sbyte)o); break;
			case TypeCode.Byte:		writer.Write((byte)o); break;
			case TypeCode.Int16:	writer.Write((short)o); break;
			case TypeCode.UInt16:	writer.Write((ushort)o); break;
			case TypeCode.Int32:	writer.Write((int)o); break;
			case TypeCode.UInt32:	writer.Write((uint)o); break;
			case TypeCode.Int64:	writer.Write((long)o); break;
			case TypeCode.UInt64:	writer.Write((ulong)o); break;
			default: return false;
			}
			return true;
		}

19 View Source File : TypeFuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz

private object[] PrepareFuzzedParametersForThisConstructor(ConstructorInfo constructor, int recursionLevel)
        {
            var parameters = new List<object>();
            var parameterInfos = constructor.GetParameters();
            foreach (var parameterInfo in parameterInfos)
            {
                var type = parameterInfo.ParameterType;

                // Default .NET types
                parameters.Add(FuzzAnyDotNetType(Type.GetTypeCode(type), type, recursionLevel));
            }

            return parameters.ToArray();
        }

19 View Source File : DarksVMInstance.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

private void Load(ulong codeAddr, uint key, DarksVMFuncSig sig, void*[] arguments, void* retTypedRef)
        {
            if(currentCtx != null)
                ctxStack.Push(currentCtx);
            currentCtx = new DarksVMContext(this);

            try
            {
                Debug.replacedert(sig.ParamTypes.Length == arguments.Length);
                currentCtx.Stack.SetTopPosition((uint) arguments.Length + 1);
                for(uint i = 0; i < arguments.Length; i++)
                {
                    var paramType = sig.ParamTypes[i];
                    if(paramType.IsByRef)
                    {
                        currentCtx.Stack[i + 1] = new DarksVMSlot {O = new TypedRef(arguments[i])};
                    }
                    else
                    {
                        var typedRef = *(TypedReference*) arguments[i];
                        currentCtx.Stack[i + 1] = DarksVMSlot.FromObject(TypedReference.ToObject(typedRef), __reftype(typedRef));
                    }
                }
                currentCtx.Stack[(uint) arguments.Length + 1] = new DarksVMSlot {U8 = 1};

                currentCtx.Registers[DarksVMConstants.REG_K1] = new DarksVMSlot {U4 = key};
                currentCtx.Registers[DarksVMConstants.REG_BP] = new DarksVMSlot {U4 = 0};
                currentCtx.Registers[DarksVMConstants.REG_SP] = new DarksVMSlot {U4 = (uint) arguments.Length + 1};
                currentCtx.Registers[DarksVMConstants.REG_IP] = new DarksVMSlot {U8 = codeAddr};
                DarksVMDispatcher.Load(currentCtx);
                Debug.replacedert(currentCtx.EHStack.Count == 0);

                if(sig.RetType != typeof(void))
                    if(sig.RetType.IsByRef)
                    {
                        var retRef = currentCtx.Registers[DarksVMConstants.REG_R0].O;
                        if(!(retRef is IReference))
                            throw new ExecutionEngineException();
                        ((IReference) retRef).ToTypedReference(currentCtx, retTypedRef, sig.RetType.GetElementType());
                    }
                    else
                    {
                        var retSlot = currentCtx.Registers[DarksVMConstants.REG_R0];
                        object retVal;
                        if(Type.GetTypeCode(sig.RetType) == TypeCode.String && retSlot.O == null)
                            retVal = Data.LookupString(retSlot.U4);
                        else
                            retVal = retSlot.ToObject(sig.RetType);
                        TypedReferenceHelpers.SetTypedRef(retVal, retTypedRef);
                    }
            }
            finally
            {
                currentCtx.Stack.FreeAllLocalloc();

                if(ctxStack.Count > 0)
                    currentCtx = ctxStack.Pop();
            }
        }

19 View Source File : DarksVMSlot.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

public static unsafe DarksVMSlot FromObject(object obj, Type type)
        {
            if(type.IsEnum)
            {
                var elemType = Enum.GetUnderlyingType(type);
                return FromObject(Convert.ChangeType(obj, elemType), elemType);
            }

            switch(Type.GetTypeCode(type))
            {
                case TypeCode.Byte:
                    return new DarksVMSlot {u1 = (byte) obj};
                case TypeCode.SByte:
                    return new DarksVMSlot {u1 = (byte) (sbyte) obj};
                case TypeCode.Boolean:
                    return new DarksVMSlot {u1 = (byte) ((bool) obj ? 1 : 0)};

                case TypeCode.UInt16:
                    return new DarksVMSlot {u2 = (ushort) obj};
                case TypeCode.Int16:
                    return new DarksVMSlot {u2 = (ushort) (short) obj};
                case TypeCode.Char:
                    return new DarksVMSlot {u2 = (char) obj};

                case TypeCode.UInt32:
                    return new DarksVMSlot {u4 = (uint) obj};
                case TypeCode.Int32:
                    return new DarksVMSlot {u4 = (uint) (int) obj};

                case TypeCode.UInt64:
                    return new DarksVMSlot {u8 = (ulong) obj};
                case TypeCode.Int64:
                    return new DarksVMSlot {u8 = (ulong) (long) obj};

                case TypeCode.Single:
                    return new DarksVMSlot {r4 = (float) obj};
                case TypeCode.Double:
                    return new DarksVMSlot {r8 = (double) obj};

                default:
                    if(obj is Pointer)
                        return new DarksVMSlot {u8 = (ulong) Pointer.Unbox(obj)};
                    if(obj is IntPtr)
                        return new DarksVMSlot {u8 = (ulong) (IntPtr) obj};
                    if(obj is UIntPtr)
                        return new DarksVMSlot {u8 = (ulong) (UIntPtr) obj};
                    if(type.IsValueType)
                        return new DarksVMSlot {o = ValueTypeBox.Box(obj, type)};
                    return new DarksVMSlot {o = obj};
            }
        }

19 View Source File : EnumCache.cs
License : MIT License
Project Creator : Abc-Arbitrage

[SuppressMessage("ReSharper", "ConvertClosureToMethodGroup")]
        public static bool IsEnumSigned(IntPtr typeHandle)
        {
            return _isEnumSigned.GetOrAdd(typeHandle, h => IsEnumSignedImpl(h));

            static bool IsEnumSignedImpl(IntPtr h)
            {
                var type = TypeUtil.GetTypeFromHandle(h) ?? throw new InvalidOperationException("Could not resolve type from handle");

                switch (Type.GetTypeCode(Enum.GetUnderlyingType(type)))
                {
                    case TypeCode.SByte:
                    case TypeCode.Int16:
                    case TypeCode.Int32:
                    case TypeCode.Int64:
                        return true;

                    case TypeCode.Byte:
                    case TypeCode.UInt16:
                    case TypeCode.UInt32:
                    case TypeCode.UInt64:
                        return false;

                    default:
                        throw new InvalidOperationException($"Invalid enum: {type}");
                }
            }
        }

19 View Source File : TypeExtensions.cs
License : MIT License
Project Creator : aliencube

public static bool IsSimpleType(this Type type)
        {
            var @enum = Type.GetTypeCode(type);
            switch (@enum)
            {
                case TypeCode.Int16:
                case TypeCode.Int32:
                case TypeCode.Int64:
                case TypeCode.Single:
                case TypeCode.Double:
                case TypeCode.Decimal:
                case TypeCode.Boolean:
                case TypeCode.DateTime:
                case TypeCode.String:
                    return true;

                case TypeCode.Object:
                    if (type == typeof(Guid))
                    {
                        return true;
                    }
                    else if (type == typeof(DateTime))
                    {
                        return true;
                    }
                    else if (type == typeof(DateTimeOffset))
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }

                case TypeCode.Empty:
                case TypeCode.DBNull:
                case TypeCode.Char:
                case TypeCode.SByte:
                case TypeCode.Byte:
                case TypeCode.UInt16:
                case TypeCode.UInt32:
                case TypeCode.UInt64:
                default:
                    return false;
            }
        }

19 View Source File : EmitHelper.cs
License : MIT License
Project Creator : 1996v

public static void EmitDefault(this ILGenerator il, Type type)
        {
            switch (Type.GetTypeCode(type))
            {
                case TypeCode.DateTime:
                    il.Emit(OpCodes.Ldsfld, typeof(DateTime).GetField(nameof(DateTime.MinValue)));
                    return;
                case TypeCode.Decimal:
                    il.Emit(OpCodes.Ldsfld, typeof(decimal).GetField(nameof(decimal.Zero)));
                    return;
                case TypeCode.Boolean:
                case TypeCode.Char:
                case TypeCode.SByte:
                case TypeCode.Byte:
                case TypeCode.Int16:
                case TypeCode.UInt16:
                case TypeCode.Int32:
                case TypeCode.UInt32:
                    il.Emit(OpCodes.Ldc_I4_0);
                    return;

                case TypeCode.Int64:
                case TypeCode.UInt64:
                    il.Emit(OpCodes.Ldc_I4_0);
                    il.Emit(OpCodes.Conv_I8);
                    return;

                case TypeCode.Single:
                    il.Emit(OpCodes.Ldc_R4, default(float));
                    return;

                case TypeCode.Double:
                    il.Emit(OpCodes.Ldc_R8, default(double));
                    return;
            }

            if (type.IsValueType)
            {
                LocalBuilder lb = il.DeclareLocal(type);
                il.Emit(OpCodes.Ldloca, lb);
                il.Emit(OpCodes.Initobj, type);
                il.Emit(OpCodes.Ldloc, lb);
            }
            else
            {
                il.Emit(OpCodes.Ldnull);
            }
        }

19 View Source File : TypeVisitor.cs
License : MIT License
Project Creator : aliencube

protected bool IsVisitable(Type type, TypeCode code)
        {
            var @enum = Type.GetTypeCode(type);
            var isVisitable = @enum == code;

            if (isVisitable)
            {
                this.Type = type;
            }

            return isVisitable;
        }

19 View Source File : ConversionHelper.cs
License : MIT License
Project Creator : abdullin

[NotNull]
		private static Func<object, object, bool> CreateTypeComparator([NotNull] Type t1, [NotNull] Type t2)
		{
			Contract.Requires(t1 != null && t2 != null);

			// note: the most common scenarios will be when we compare 'A' to "A", or (int)123 to (long)123, Guids in string or System.Guid form, ...
			// We should not try too hard to compare complex objects (what about dates ? timespans? Guids?)

			// first, handle the easy cases
			if (AreEquivalentTypes(t1, t2))
			{
				switch (Type.GetTypeCode(t1))
				{
					case TypeCode.Char: return (x, y) => (char)x == (char)y;
					case TypeCode.Byte: return (x, y) => (byte)x == (byte)y;
					case TypeCode.SByte: return (x, y) => (sbyte)x == (sbyte)y;
					case TypeCode.Int16: return (x, y) => (short)x == (short)y;
					case TypeCode.UInt16: return (x, y) => (ushort)x == (ushort)y;
					case TypeCode.Int32: return (x, y) => (int)x == (int)y;
					case TypeCode.UInt32: return (x, y) => (uint)x == (uint)y;
					case TypeCode.Int64: return (x, y) => (long)x == (long)y;
					case TypeCode.UInt64: return (x, y) => (ulong)x == (ulong)y;
					case TypeCode.Single: return (x, y) => (float)x == (float)y;
					case TypeCode.Double: return (x, y) => (double)x == (double)y;
					case TypeCode.String: return (x, y) => (string)x == (string)y;
				}

				return (x, y) =>
				{
					if (object.ReferenceEquals(x, null)) return object.ReferenceEquals(y, null);
					return object.ReferenceEquals(x, y) || x.Equals(y);
				};
			}

			if (IsStringType(t1) || IsStringType(t2))
			{
				return (x, y) =>
				{
					if (x == null) return y == null;
					if (y == null) return false;
					return object.ReferenceEquals(x, y) || (TryAdaptToString(x) == TryAdaptToString(y));
				};
			}

			if (IsNumericType(t1) || IsNumericType(t2))
			{
				if (IsDecimalType(t1) || IsDecimalType(t2))
				{
					return (x, y) =>
					{
						double d1, d2;
						return x == null ? y == null : y != null && TryAdaptToDecimal(x, t1, out d1) && TryAdaptToDecimal(y, t2, out d2) && d1 == d2;
					};
				}
				else
				{
					//TODO: handle UInt64 with values > long.MaxValue that will overflow to negative values when casted down to Int64
					return (x, y) =>
					{
						long l1, l2;
						return x == null ? y == null : y != null && TryAdaptToInteger(x, t1, out l1) && TryAdaptToInteger(y, t2, out l2) && l1 == l2;
					};
				}
			}

			//TODO: some other way to compare ?
			return (x, y) => false;
		}

19 View Source File : TypeHelper.cs
License : MIT License
Project Creator : anthonyreilly

public static bool IsInteger(Type type)
        {
            var nnType = GetNonNullableType(type);
            switch (Type.GetTypeCode(type))
            {
                case TypeCode.SByte:
                case TypeCode.Int16:
                case TypeCode.Int32:
                case TypeCode.Int64:
                case TypeCode.Byte:
                case TypeCode.UInt16:
                case TypeCode.UInt32:
                case TypeCode.UInt64:
                    return true;

                case TypeCode.Boolean:
                case TypeCode.Char:
                case TypeCode.DateTime:
                case TypeCode.Decimal:
                case TypeCode.Double:
                case TypeCode.Empty:
                case TypeCode.Object:
                case TypeCode.Single:
                case TypeCode.String:
                default:
                    return false;        
            }
        }

19 View Source File : SqlServerDbAdapter.cs
License : MIT License
Project Creator : 17MKH

public override void ResolveColumn(IColumnDescriptor columnDescriptor)
    {
        var propertyType = columnDescriptor.PropertyInfo.PropertyType;
        var isNullable = propertyType.IsNullable();
        if (isNullable)
        {
            propertyType = Nullable.GetUnderlyingType(propertyType);
            if (propertyType == null)
                throw new Exception("Property2Column error");
        }

        if (propertyType.IsEnum)
        {
            if (!isNullable)
            {
                columnDescriptor.DefaultValue = "0";
            }

            columnDescriptor.TypeName = "SMALLINT";
            return;
        }

        if (propertyType.IsGuid())
        {
            columnDescriptor.TypeName = "UNIQUEIDENTIFIER";

            return;
        }

        var typeCode = Type.GetTypeCode(propertyType);
        switch (typeCode)
        {
            case TypeCode.Char:
            case TypeCode.String:
                columnDescriptor.TypeName = "NVARCHAR";
                break;
            case TypeCode.Boolean:
                if (!isNullable)
                {
                    columnDescriptor.DefaultValue = "0";
                }

                columnDescriptor.TypeName = "BIT";
                break;
            case TypeCode.Byte:
                if (!isNullable)
                {
                    columnDescriptor.DefaultValue = "0";
                }
                columnDescriptor.TypeName = "TINYINT";
                break;
            case TypeCode.Int16:
            case TypeCode.Int32:
                if (!isNullable)
                {
                    columnDescriptor.DefaultValue = "0";
                }

                columnDescriptor.TypeName = "INT";
                break;
            case TypeCode.Int64:
                if (!isNullable)
                {
                    columnDescriptor.DefaultValue = "0";
                }

                columnDescriptor.TypeName = "BIGINT";
                break;
            case TypeCode.DateTime:
                if (!isNullable)
                {
                    columnDescriptor.DefaultValue = "GETDATE()";
                }
                columnDescriptor.TypeName = "DATETIME";
                break;
            case TypeCode.Decimal:
                if (!isNullable)
                {
                    columnDescriptor.DefaultValue = "0";
                }

                columnDescriptor.TypeName = "DECIMAL";
                break;
            case TypeCode.Double:
            case TypeCode.Single:
                if (!isNullable)
                {
                    columnDescriptor.DefaultValue = "0";
                }

                columnDescriptor.TypeName = "FLOAT";
                break;
        }

        //主键默认值为null
        if (columnDescriptor.IsPrimaryKey)
        {
            columnDescriptor.DefaultValue = null;
        }
    }

19 View Source File : Constant.cs
License : GNU General Public License v3.0
Project Creator : anydream

static ElementType GetElementType(object value) {
			if (value == null)
				return ElementType.Clreplaced;
			switch (System.Type.GetTypeCode(value.GetType())) {
			case TypeCode.Boolean:	return ElementType.Boolean;
			case TypeCode.Char:		return ElementType.Char;
			case TypeCode.SByte:	return ElementType.I1;
			case TypeCode.Byte:		return ElementType.U1;
			case TypeCode.Int16:	return ElementType.I2;
			case TypeCode.UInt16:	return ElementType.U2;
			case TypeCode.Int32:	return ElementType.I4;
			case TypeCode.UInt32:	return ElementType.U4;
			case TypeCode.Int64:	return ElementType.I8;
			case TypeCode.UInt64:	return ElementType.U8;
			case TypeCode.Single:	return ElementType.R4;
			case TypeCode.Double:	return ElementType.R8;
			case TypeCode.String:	return ElementType.String;
			default: return ElementType.Void;
			}
		}

19 View Source File : Box.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

public void Load(DarksVMContext ctx, out ExecutionState state)
        {
            var sp = ctx.Registers[DarksVMConstants.REG_SP].U4;
            var typeSlot = ctx.Stack[sp--];
            var valSlot = ctx.Stack[sp];

            var valType = (Type) ctx.Instance.Data.LookupReference(typeSlot.U4);
            if(Type.GetTypeCode(valType) == TypeCode.String && valSlot.O == null)
            {
                valSlot.O = ctx.Instance.Data.LookupString(valSlot.U4);
            }
            else
            {
                Debug.replacedert(valType.IsValueType);
                valSlot.O = valSlot.ToObject(valType);
            }
            ctx.Stack[sp] = valSlot;

            ctx.Stack.SetTopPosition(sp);
            ctx.Registers[DarksVMConstants.REG_SP].U4 = sp;
            state = ExecutionState.Next;
        }

19 View Source File : Cast.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

public void Load(DarksVMContext ctx, out ExecutionState state)
        {
            var sp = ctx.Registers[DarksVMConstants.REG_SP].U4;
            var typeSlot = ctx.Stack[sp--];
            var valSlot = ctx.Stack[sp];

            var castclreplaced = (typeSlot.U4 & 0x80000000) != 0;
            var castType = (Type) ctx.Instance.Data.LookupReference(typeSlot.U4 & ~0x80000000);
            if(Type.GetTypeCode(castType) == TypeCode.String && valSlot.O == null)
            {
                valSlot.O = ctx.Instance.Data.LookupString(valSlot.U4);
            }
            else if(valSlot.O == null)
            {
                valSlot.O = null;
            }
            else if(!castType.IsInstanceOfType(valSlot.O))
            {
                valSlot.O = null;
                if(castclreplaced)
                    throw new InvalidCastException();
            }
            ctx.Stack[sp] = valSlot;

            ctx.Stack.SetTopPosition(sp);
            ctx.Registers[DarksVMConstants.REG_SP].U4 = sp;
            state = ExecutionState.Next;
        }

19 View Source File : DefaultRedisSerializer.cs
License : MIT License
Project Creator : 17MKH

public object Deserialize(RedisValue value, Type type)
    {
        if (Type.GetTypeCode(type) == TypeCode.Object)
        {
            return JsonSerializer.Deserialize(value,type);
        }

        return value;
    }

19 View Source File : Ecall.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

private static IReference PopRef(DarksVMContext ctx, Type type, ref uint sp)
        {
            var arg = ctx.Stack[sp];

            if(type.IsByRef)
            {
                sp--;
                type = type.GetElementType();
                if(arg.O is Pointer)
                {
                    var ptr = Pointer.Unbox(arg.O);
                    return new PointerRef(ptr);
                }
                if(arg.O is IReference) return (IReference) arg.O;
                return new PointerRef((void*) arg.U8);
            }
            if(Type.GetTypeCode(type) == TypeCode.String && arg.O == null)
            {
                arg.O = ctx.Instance.Data.LookupString(arg.U4);
                ctx.Stack[sp] = arg;
            }
            return new StackRef(sp--);
        }

19 View Source File : NpcCommandHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

private bool CheckField(PlayerEnreplacedy player, string field, string strValue, string strRelation)
        {
            try
            {
                var relations = GetRelations(strRelation);// 1 大于,0 等于 ,-1 小于

                var fieldProp = GetFieldPropertyInfo(player, field);
                if (fieldProp == null)
                {
                    return false;
                }

                var objectValue = fieldProp.GetValue(player);
                var typeCode = Type.GetTypeCode(fieldProp.GetType());
                switch (typeCode)
                {
                    case TypeCode.Int32:
                        return relations.Contains(Convert.ToInt32(strValue).CompareTo(Convert.ToInt32(objectValue)));

                    case TypeCode.Int64:
                        return relations.Contains(Convert.ToInt64(strValue).CompareTo(Convert.ToInt64(objectValue)));

                    case TypeCode.Decimal:
                        return relations.Contains(Convert.ToDecimal(strValue).CompareTo(Convert.ToDecimal(objectValue)));

                    case TypeCode.Double:
                        return relations.Contains(Convert.ToDouble(strValue).CompareTo(Convert.ToDouble(objectValue)));

                    case TypeCode.Boolean:
                        return relations.Contains(Convert.ToBoolean(strValue).CompareTo(Convert.ToBoolean(objectValue)));

                    case TypeCode.DateTime:
                        return relations.Contains(Convert.ToDateTime(strValue).CompareTo(Convert.ToDateTime(objectValue)));

                    case TypeCode.String:
                        return relations.Contains(strValue.CompareTo(objectValue));

                    default:
                        throw new Exception($"不支持的数据类型: {typeCode}");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"CheckField Exception:{ex}");
                return false;
            }
        }

19 View Source File : DarksVMInstance.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

private object Load(ulong codeAddr, uint key, DarksVMFuncSig sig, object[] arguments)
        {
            if(currentCtx != null)
                ctxStack.Push(currentCtx);
            currentCtx = new DarksVMContext(this);

            try
            {
                Debug.replacedert(sig.ParamTypes.Length == arguments.Length);
                currentCtx.Stack.SetTopPosition((uint) arguments.Length + 1);
                for(uint i = 0; i < arguments.Length; i++) currentCtx.Stack[i + 1] = DarksVMSlot.FromObject(arguments[i], sig.ParamTypes[i]);
                currentCtx.Stack[(uint) arguments.Length + 1] = new DarksVMSlot {U8 = 1};

                currentCtx.Registers[DarksVMConstants.REG_K1] = new DarksVMSlot {U4 = key};
                currentCtx.Registers[DarksVMConstants.REG_BP] = new DarksVMSlot {U4 = 0};
                currentCtx.Registers[DarksVMConstants.REG_SP] = new DarksVMSlot {U4 = (uint) arguments.Length + 1};
                currentCtx.Registers[DarksVMConstants.REG_IP] = new DarksVMSlot {U8 = codeAddr};
                DarksVMDispatcher.Load(currentCtx);
                Debug.replacedert(currentCtx.EHStack.Count == 0);

                object retVal = null;
                if(sig.RetType != typeof(void))
                {
                    var retSlot = currentCtx.Registers[DarksVMConstants.REG_R0];
                    if(Type.GetTypeCode(sig.RetType) == TypeCode.String && retSlot.O == null)
                        retVal = Data.LookupString(retSlot.U4);
                    else
                        retVal = retSlot.ToObject(sig.RetType);
                }

                return retVal;
            }
            finally
            {
                currentCtx.Stack.FreeAllLocalloc();

                if(ctxStack.Count > 0)
                    currentCtx = ctxStack.Pop();
            }
        }

19 View Source File : DarksVMSlot.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

public unsafe object ToObject(Type type)
        {
            if(type.IsEnum)
                return Enum.ToObject(type, ToObject(Enum.GetUnderlyingType(type)));

            switch(Type.GetTypeCode(type))
            {
                case TypeCode.Byte:
                    return u1;
                case TypeCode.SByte:
                    return (sbyte) u1;
                case TypeCode.Boolean:
                    return u1 != 0;

                case TypeCode.UInt16:
                    return u2;
                case TypeCode.Int16:
                    return (short) u2;
                case TypeCode.Char:
                    return (char) u2;

                case TypeCode.UInt32:
                    return u4;
                case TypeCode.Int32:
                    return (int) u4;

                case TypeCode.UInt64:
                    return u8;
                case TypeCode.Int64:
                    return (long) u8;

                case TypeCode.Single:
                    return r4;
                case TypeCode.Double:
                    return r8;

                default:
                    if(type.IsPointer)
                        return Pointer.Box((void*) u8, type);
                    if(type == typeof(IntPtr))
                        return Platform.x64 ? new IntPtr((long) u8) : new IntPtr((int) u4);
                    if(type == typeof(UIntPtr))
                        return Platform.x64 ? new UIntPtr(u8) : new UIntPtr(u4);
                    return ValueTypeBox.Unbox(o);
            }
        }

19 View Source File : EnumCache.cs
License : MIT License
Project Creator : Abc-Arbitrage

internal static ulong ToUInt64Slow(Enum value)
        {
            switch (Type.GetTypeCode(Enum.GetUnderlyingType(value.GetType())))
            {
                case TypeCode.SByte:
                    return ToUInt64((sbyte)(object)value);

                case TypeCode.Byte:
                    return ToUInt64((byte)(object)value);

                case TypeCode.Int16:
                    return ToUInt64((short)(object)value);

                case TypeCode.UInt16:
                    return ToUInt64((ushort)(object)value);

                case TypeCode.Int32:
                    return ToUInt64((int)(object)value);

                case TypeCode.UInt32:
                    return ToUInt64((uint)(object)value);

                case TypeCode.Int64:
                    return ToUInt64((long)(object)value);

                case TypeCode.UInt64:
                    return ToUInt64((ulong)(object)value);

                default:
                    throw new InvalidOperationException($"Invalid enum: {value.GetType()}");
            }
        }

19 View Source File : LinqToSql.cs
License : MIT License
Project Creator : AlenToma

protected Expression VisitConstantFixed(ConstantExpression c, string memName = "")
        {
            IQueryable q = c.Value as IQueryable;
            var StringifyText = StringyFyExp.Matches(sb.ToString()).Cast<Match>().FirstOrDefault();
            var isEnum = StringifyText != null;
            string type = null;
            if (isEnum)
                type = CleanText();
            if (q == null && c.Value == null)
            {
                sb.Append("NULL");
            }
            else if (q == null)
            {
                switch (Type.GetTypeCode(c.Value.GetType()))
                {
                    case TypeCode.Boolean:
                        sb.Append(((bool)c.Value) ? (DataBaseTypes == DataBaseTypes.PostgreSql ? "true" : "1") : (DataBaseTypes == DataBaseTypes.PostgreSql ? "false" : "0"));
                        break;

                    case TypeCode.String:
                        CleanDecoder(string.Format("String[{0}]", c.Value));
                        break;

                    case TypeCode.DateTime:
                        CleanDecoder(string.Format("Date[{0}]", c.Value));
                        break;

                    case TypeCode.Object:

                        object value = null;
                        Type fieldType = null;
                        if (c.Value.GetType().GetFields(_bindingFlags).Length > 0 && (string.IsNullOrEmpty(memName) || c.Value.GetType().GetFields(_bindingFlags).Any(x => x.Name == memName)))
                        {
                            var field = string.IsNullOrEmpty(memName)
                                 ? c.Value.GetType().GetFields(_bindingFlags).FirstOrDefault()
                                 : c.Value.GetType().GetFields(_bindingFlags).FirstOrDefault(x => x.Name == memName);
                            fieldType = field?.FieldType;

                            value = field?.GetValue(c.Value);

                        }
                        else
                        {
                            var field = string.IsNullOrEmpty(memName)
                            ? c.Value.GetType().GetProperties().FirstOrDefault()
                            : c.Value.GetType().GetProperties().FirstOrDefault(x => x.Name == memName);
                            fieldType = field?.PropertyType;
                            value = field?.GetValue(c.Value);
                        }



                        if (value == null && fieldType == null)
                            break;
                        CleanDecoder(ValuetoSql(value, isEnum, fieldType));
                        break;
                    default:
                        if (isEnum && SavedTypes.ContainsKey(type))
                        {
                            var enumtype = SavedTypes[type];
                            var v = c.Value.ConvertValue(enumtype);
                            CleanDecoder(ValuetoSql(v, isEnum));
                            break;
                        }
                        CleanDecoder(ValuetoSql(c.Value, isEnum));
                        break;
                }
            }

            return c;
        }

19 View Source File : SqliteDbAdapter.cs
License : MIT License
Project Creator : 17MKH

public override void ResolveColumn(IColumnDescriptor descriptor)
    {
        var propertyType = descriptor.PropertyInfo.PropertyType;
        var isNullable = propertyType.IsNullable();
        if (isNullable)
        {
            propertyType = Nullable.GetUnderlyingType(propertyType);
            if (propertyType == null)
                throw new Exception("Property2Column error");
        }

        if (propertyType.IsEnum)
        {
            if (!isNullable)
            {
                descriptor.DefaultValue = "0";
            }

            descriptor.TypeName = "integer";
            return;
        }

        if (propertyType.IsGuid())
        {
            descriptor.TypeName = "UNIQUEIDENTIFIER";

            return;
        }

        var typeCode = Type.GetTypeCode(propertyType);
        switch (typeCode)
        {
            case TypeCode.Boolean:
            case TypeCode.Byte:
            case TypeCode.Int16:
            case TypeCode.Int32:
            case TypeCode.Int64:
                descriptor.TypeName = "integer";
                break;
            case TypeCode.Decimal:
            case TypeCode.Double:
            case TypeCode.Single:
                descriptor.TypeName = "decimal";
                break;
            default:
                descriptor.TypeName = "text";
                break;
        }
    }

19 View Source File : Variable.Steps.cs
License : MIT License
Project Creator : alfa-laboratory

[StepArgumentTransformation]
        public TypeCode StringToTypeCode(string type)
        {
            var variablesType = new Dictionary<string, Type>
            {
                { "int", typeof(int)},
                { "string", typeof(string)},
                { "double", typeof(double)},
                { "bool", typeof(bool)},
                { "object",typeof(object)},
                { "long",typeof(long)},
                { "float",typeof(float)}
            };
            type.Should().NotBeNull("Значение \"type\" не задано");
            type = type.ToLower();
            if (!variablesType.TryGetValue(type, out var value)) throw new NotValidTypeException($"There is no type \"{type}\"");
            return Type.GetTypeCode(value);
        }

19 View Source File : FdbTuplePackers.cs
License : MIT License
Project Creator : abdullin

public static void SerializeObjectTo(ref TupleWriter writer, object value)
		{
			if (value == null)
			{ // null value
			  // includes all null references to ref types, as nullables where HasValue == false
				FdbTupleParser.WriteNil(ref writer);
				return;
			}

			switch (Type.GetTypeCode(value.GetType()))
			{
				case TypeCode.Empty:
				case TypeCode.Object:
					{
						byte[] bytes = value as byte[];
						if (bytes != null)
						{
							SerializeTo(ref writer, bytes);
							return;
						}

						if (value is Slice)
						{
							SerializeTo(ref writer, (Slice)value);
							return;
						}

						if (value is Guid)
						{
							SerializeTo(ref writer, (Guid)value);
							return;
						}

						if (value is Uuid128)
						{
							SerializeTo(ref writer, (Uuid128)value);
							return;
						}

						if (value is Uuid64)
						{
							SerializeTo(ref writer, (Uuid64)value);
							return;
						}

						if (value is TimeSpan)
						{
							SerializeTo(ref writer, (TimeSpan)value);
							return;
						}

						if (value is FdbTupleAlias)
						{
							SerializeTo(ref writer, (FdbTupleAlias)value);
							return;
						}

						break;
					}
				case TypeCode.DBNull:
					{ // same as null
						FdbTupleParser.WriteNil(ref writer);
						return;
					}
				case TypeCode.Boolean:
					{
						SerializeTo(ref writer, (bool)value);
						return;
					}
				case TypeCode.Char:
					{
						// should be treated as a string with only one char
						SerializeTo(ref writer, (char)value);
						return;
					}
				case TypeCode.SByte:
					{
						SerializeTo(ref writer, (sbyte)value);
						return;
					}
				case TypeCode.Byte:
					{
						SerializeTo(ref writer, (byte)value);
						return;
					}
				case TypeCode.Int16:
					{
						SerializeTo(ref writer, (short)value);
						return;
					}
				case TypeCode.UInt16:
					{
						SerializeTo(ref writer, (ushort)value);
						return;
					}
				case TypeCode.Int32:
					{
						SerializeTo(ref writer, (int)value);
						return;
					}
				case TypeCode.UInt32:
					{
						SerializeTo(ref writer, (uint)value);
						return;
					}
				case TypeCode.Int64:
					{
						SerializeTo(ref writer, (long)value);
						return;
					}
				case TypeCode.UInt64:
					{
						SerializeTo(ref writer, (ulong)value);
						return;
					}
				case TypeCode.String:
					{
						SerializeTo(ref writer, value as string);
						return;
					}
				case TypeCode.DateTime:
					{
						SerializeTo(ref writer, (DateTime)value);
						return;
					}
				case TypeCode.Double:
					{
						SerializeTo(ref writer, (double)value);
						return;
					}
				case TypeCode.Single:
					{
						SerializeTo(ref writer, (float)value);
						return;
					}
			}

			var tuple = value as IFdbTuple;
			if (tuple != null)
			{
				SerializeTupleTo(ref writer, tuple);
				return;
			}

			var fmt = value as ITupleFormattable;
			if (fmt != null)
			{
				tuple = fmt.ToTuple();
				if (tuple == null) throw new InvalidOperationException(String.Format("An instance of type {0} returned a null Tuple while serialiazing", value.GetType().Name));
				SerializeTupleTo(ref writer, tuple);
				return;
			}

			// Not Supported ?
			throw new NotSupportedException(String.Format("Doesn't know how to serialize objects of type {0} into Tuple Encoding format", value.GetType().Name));
		}

19 View Source File : TypeExtensions.cs
License : MIT License
Project Creator : aliencube

public static bool IsReferentialType(this Type type)
        {
            var @enum = Type.GetTypeCode(type);
            var isReferential = @enum == TypeCode.Object;

            if (type == typeof(Guid))
            {
                isReferential = false;
            }
            if (type == typeof(DateTime))
            {
                isReferential = false;
            }
            if (type == typeof(DateTimeOffset))
            {
                isReferential = false;
            }
            if (type.IsOpenApiNullable())
            {
                isReferential = false;
            }
            if (type.IsUnflaggedEnumType())
            {
                isReferential = false;
            }
            if (type.IsJObjectType())
            {
                isReferential = false;
            }

            return isReferential;
        }

19 View Source File : EntityDescriptor.cs
License : MIT License
Project Creator : 17MKH

private void SetColumns()
    {
        //加载属性列表
        var properties = new List<PropertyInfo>();
        foreach (var p in EnreplacedyType.GetProperties())
        {
            var type = p.PropertyType;
            if (type == typeof(TimeSpan) || (!type.IsGenericType || type.IsNullable()) && (type.IsGuid() || type.IsNullable() || Type.GetTypeCode(type) != TypeCode.Object)
                && Attribute.GetCustomAttributes(p).All(attr => attr.GetType() != typeof(NotMappingColumnAttribute)))
            {
                properties.Add(p);
            }
        }

        foreach (var p in properties)
        {
            var column = new ColumnDescriptor(p, DbContext.Adapter);

            if (column.IsPrimaryKey)
            {
                PrimaryKey = new PrimaryKeyDescriptor(p);
                Columns.Insert(0, column);
            }
            else
            {
                Columns.Add(column);
            }
        }

        //如果主键为null,则需要指定为没有主键
        if (PrimaryKey == null)
        {
            PrimaryKey = new PrimaryKeyDescriptor();
        }
    }

19 View Source File : EnumExtensions.cs
License : MIT License
Project Creator : aliencube

public static string ToDataFormat(this Type type)
        {
            var @enum = Type.GetTypeCode(type);
            if (!type.IsNullOrDefault() && type.IsEnum)
            {
                @enum = TypeCode.String;
            }

            switch (@enum)
            {
                case TypeCode.Int16:
                case TypeCode.Int32:
                    return "int32";

                case TypeCode.Int64:
                    return "int64";

                case TypeCode.Single:
                    return "float";

                case TypeCode.Double:
                case TypeCode.Decimal:
                    return "double";

                case TypeCode.DateTime:
                    return "date-time";

                case TypeCode.Char:
                case TypeCode.SByte:
                case TypeCode.Byte:
                case TypeCode.UInt16:
                case TypeCode.UInt32:
                case TypeCode.UInt64:
                case TypeCode.Boolean:
                case TypeCode.String:
                    return null;

                case TypeCode.Object:
                    if (type == typeof(Guid))
                    {
                        return "uuid";
                    }
                    else if (type == typeof(DateTime))
                    {
                        return "date-time";
                    }
                    else if (type == typeof(DateTimeOffset))
                    {
                        return "date-time";
                    }
                    else
                    {
                        return null;
                    }

                case TypeCode.Empty:
                case TypeCode.DBNull:
                default:
                    throw new InvalidOperationException("Invalid data type");
            }
        }

19 View Source File : ConversionHelper.cs
License : MIT License
Project Creator : abdullin

internal static bool TryAdaptToInteger(object value, [NotNull] Type type, out long result)
		{
			if (value != null)
			{
				switch (Type.GetTypeCode(type))
				{
					case TypeCode.Int16: { result = (short)value; return true; }
					case TypeCode.UInt16: { result = (ushort)value; return true; }
					case TypeCode.Int32: { result = (int)value; return true; }
					case TypeCode.UInt32: { result = (uint)value; return true; }
					case TypeCode.Int64: { result = (long)value; return true; }
					case TypeCode.UInt64: { result = (long)(ulong)value; return true; }
					case TypeCode.Single: { result = (long)(float)value; return true; }
					case TypeCode.Double: { result = (long)(double)value; return true; }
				}
			}
			result = 0;
			return false;
		}

19 View Source File : TypeExtensions.cs
License : MIT License
Project Creator : anet-team

public static bool IsSimpleType(this Type type)
        {
            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
                type = type.GetGenericArguments()[0]; // or  Nullable.GetUnderlyingType(type)

            if (type.IsEnum)
                return true;

            if (type == typeof(Guid))
                return true;

            TypeCode tc = Type.GetTypeCode(type);
            switch (tc)
            {
                case TypeCode.Byte:
                case TypeCode.SByte:
                case TypeCode.Int16:
                case TypeCode.Int32:
                case TypeCode.Int64:
                case TypeCode.UInt16:
                case TypeCode.UInt32:
                case TypeCode.UInt64:
                case TypeCode.Single:
                case TypeCode.Double:
                case TypeCode.Decimal:
                case TypeCode.Char:
                case TypeCode.String:
                case TypeCode.Boolean:
                case TypeCode.DateTime:
                    return true;
                case TypeCode.Object:
                    return (typeof(TimeSpan) == type) || (typeof(DateTimeOffset) == type);
                default:
                    return false;
            }
        }

19 View Source File : Helpers.cs
License : MIT License
Project Creator : 404Lcc

public static ProtoTypeCode GetTypeCode(System.Type type)
        {
#if WINRT || COREFX || PROFILE259
			if (IsEnum(type))
            {
                type = Enum.GetUnderlyingType(type);
            }
            int idx = Array.IndexOf<Type>(knownTypes, type);
            if (idx >= 0) return knownCodes[idx];
            return type == null ? ProtoTypeCode.Empty : ProtoTypeCode.Unknown;
#else
            TypeCode code = System.Type.GetTypeCode(type);
            switch (code)
            {
                case TypeCode.Empty:
                case TypeCode.Boolean:
                case TypeCode.Char:
                case TypeCode.SByte:
                case TypeCode.Byte:
                case TypeCode.Int16:
                case TypeCode.UInt16:
                case TypeCode.Int32:
                case TypeCode.UInt32:
                case TypeCode.Int64:
                case TypeCode.UInt64:
                case TypeCode.Single:
                case TypeCode.Double:
                case TypeCode.Decimal:
                case TypeCode.DateTime:
                case TypeCode.String:
                    return (ProtoTypeCode)code;
            }

            if (type.FullName == typeof(TimeSpan).FullName) return ProtoTypeCode.TimeSpan;
            if (type.FullName == typeof(Guid).FullName) return ProtoTypeCode.Guid;
            if (type.FullName == typeof(Uri).FullName) return ProtoTypeCode.Uri;
#if PORTABLE
            // In PCLs, the Uri type may not match (WinRT uses Internal/Uri, .Net uses System/Uri), so match on the full name instead
            if (type.FullName == typeof(Uri).FullName) return ProtoTypeCode.Uri;
#endif
            if (type.FullName == typeof(byte[]).FullName) return ProtoTypeCode.ByteArray;
            if (type.FullName == typeof(System.Type).FullName) return ProtoTypeCode.Type;

            return ProtoTypeCode.Unknown;
#endif
        }

19 View Source File : Helpers.cs
License : MIT License
Project Creator : AnotherEnd15

public static ProtoTypeCode GetTypeCode(Type type)
        {
#if COREFX || PROFILE259
            if (IsEnum(type))
            {
                type = Enum.GetUnderlyingType(type);
            }
            int idx = Array.IndexOf<Type>(knownTypes, type);
            if (idx >= 0) return knownCodes[idx];
            return type == null ? ProtoTypeCode.Empty : ProtoTypeCode.Unknown;
#else
            TypeCode code = Type.GetTypeCode(type);
            switch (code)
            {
                case TypeCode.Empty:
                case TypeCode.Boolean:
                case TypeCode.Char:
                case TypeCode.SByte:
                case TypeCode.Byte:
                case TypeCode.Int16:
                case TypeCode.UInt16:
                case TypeCode.Int32:
                case TypeCode.UInt32:
                case TypeCode.Int64:
                case TypeCode.UInt64:
                case TypeCode.Single:
                case TypeCode.Double:
                case TypeCode.Decimal:
                case TypeCode.DateTime:
                case TypeCode.String:
                    return (ProtoTypeCode)code;
            }
            if (type == typeof(TimeSpan)) return ProtoTypeCode.TimeSpan;
            if (type == typeof(Guid)) return ProtoTypeCode.Guid;
            if (type == typeof(Uri)) return ProtoTypeCode.Uri;
#if PORTABLE
            // In PCLs, the Uri type may not match (WinRT uses Internal/Uri, .Net uses System/Uri), so match on the full name instead
            if (type.FullName == typeof(Uri).FullName) return ProtoTypeCode.Uri;
#endif
            if (type == typeof(byte[])) return ProtoTypeCode.ByteArray;
            if (type == typeof(Type)) return ProtoTypeCode.Type;

            return ProtoTypeCode.Unknown;
#endif
        }

19 View Source File : ConversionHelper.cs
License : MIT License
Project Creator : abdullin

private static bool IsNumericType([NotNull] Type t)
		{
			// Return true for valuetypes that are considered numbers.
			// Notes:
			// - We do not consider 'byte' to be a number, because we will serialize it as a byte[1]
			// - We do not consider 'char' to be a number, because we will serialize it as a string
			// - For nullable types, we consider the underlying type, so "int?" is considered to be a number"

			switch (Type.GetTypeCode(t))
			{
				case TypeCode.SByte:
				case TypeCode.Int16:
				case TypeCode.UInt16:
				case TypeCode.Int32:
				case TypeCode.UInt32:
				case TypeCode.Int64:
				case TypeCode.UInt64:
				case TypeCode.Single:
				case TypeCode.Double:
					return true;

				case TypeCode.Object:
					{
						// Could be a Nullable<T>
						var nullableType = Nullable.GetUnderlyingType(t);
						return nullableType != null && IsNumericType(nullableType);
					}
				default:
					{
						return false;
					}
			}
		}

19 View Source File : CustomAttributeWriter.cs
License : GNU General Public License v3.0
Project Creator : anydream

static bool VerifyValue(object o, ElementType etype) {
			if (o == null)
				return false;

			switch (Type.GetTypeCode(o.GetType())) {
			case TypeCode.Boolean:	return etype == ElementType.Boolean;
			case TypeCode.Char:		return etype == ElementType.Char;
			case TypeCode.SByte:	return etype == ElementType.I1;
			case TypeCode.Byte:		return etype == ElementType.U1;
			case TypeCode.Int16:	return etype == ElementType.I2;
			case TypeCode.UInt16:	return etype == ElementType.U2;
			case TypeCode.Int32:	return etype == ElementType.I4;
			case TypeCode.UInt32:	return etype == ElementType.U4;
			case TypeCode.Int64:	return etype == ElementType.I8;
			case TypeCode.UInt64:	return etype == ElementType.U8;
			case TypeCode.Single:	return etype == ElementType.R4;
			case TypeCode.Double:	return etype == ElementType.R8;
			default: return false;
			}
		}

19 View Source File : Protocol16Serializer.cs
License : MIT License
Project Creator : 0blu

public static void Serialize(Protocol16Stream output, object obj, bool writeTypeCode)
        {
            if (obj == null)
            {
                output.WriteTypeCodeIfTrue(Protocol16Type.Null, writeTypeCode);
                return;
            }

            Protocol16Type type = TypeCodeToProtocol16Type(obj.GetType());
            switch (type)
            {
                case Protocol16Type.Boolean:
                    SerializeBoolean(output, (bool)obj, writeTypeCode);
                    return;
                case Protocol16Type.Byte:
                    SerializeByte(output, (byte)obj, writeTypeCode);
                    return;
                case Protocol16Type.Short:
                    SerializeShort(output, (short)obj, writeTypeCode);
                    return;
                case Protocol16Type.Integer:
                    SerializeInteger(output, (int)obj, writeTypeCode);
                    return;
                case Protocol16Type.Long:
                    SerializeLong(output, (long)obj, writeTypeCode);
                    return;
                case Protocol16Type.Float:
                    SerializeFloat(output, (float)obj, writeTypeCode);
                    return;
                case Protocol16Type.Double:
                    SerializeDouble(output, (double)obj, writeTypeCode);
                    return;
                case Protocol16Type.String:
                    SerializeString(output, (string)obj, writeTypeCode);
                    return;
                case Protocol16Type.EventData:
                    SerializeEventData(output, (EventData)obj, writeTypeCode);
                    return;
                case Protocol16Type.Hashtable:
                    SerializeHashtable(output, (Hashtable)obj, writeTypeCode);
                    return;
                case Protocol16Type.Dictionary:
                    SerializeDictionary(output, (IDictionary)obj, writeTypeCode);
                    return;
                case Protocol16Type.OperationResponse:
                    SerializeOperationResponse(output, (OperationResponse)obj, writeTypeCode);
                    return;
                case Protocol16Type.OperationRequest:
                    SerializeOperationRequest(output, (OperationRequest)obj, writeTypeCode);
                    return;
                case Protocol16Type.IntegerArray:
                case Protocol16Type.StringArray:
                case Protocol16Type.ByteArray:
                case Protocol16Type.ObjectArray:
                case Protocol16Type.Array:
                    SerializeAnyArray(output, (Array)obj, writeTypeCode, type);
                    return;
            }

            // Special case
            if (obj is ArraySegment<byte> arraySegment)
            {
                SerializeArraySegment(output, arraySegment, writeTypeCode);
                return;
            }

            throw new ArgumentException($"Cannot serialize objects of type {obj.GetType()} / System.TypeCode: {Type.GetTypeCode(obj.GetType())}");
        }

19 View Source File : CustomAttributeWriter.cs
License : GNU General Public License v3.0
Project Creator : anydream

static bool ToDouble(object o, out double result) {
			if (o == null) {
				result = double.NaN;
				return false;
			}

			switch (Type.GetTypeCode(o.GetType())) {
			case TypeCode.Boolean:
				result = (bool)o ? 1 : 0;
				return true;

			case TypeCode.Char:
				result = (ushort)(char)o;
				return true;

			case TypeCode.SByte:
				result = (sbyte)o;
				return true;

			case TypeCode.Byte:
				result = (byte)o;
				return true;

			case TypeCode.Int16:
				result = (short)o;
				return true;

			case TypeCode.UInt16:
				result = (ushort)o;
				return true;

			case TypeCode.Int32:
				result = (int)o;
				return true;

			case TypeCode.UInt32:
				result = (uint)o;
				return true;

			case TypeCode.Int64:
				result = (long)o;
				return true;

			case TypeCode.UInt64:
				result = (ulong)o;
				return true;

			case TypeCode.Single:
				result = (float)o;
				return true;

			case TypeCode.Double:
				result = (double)o;
				return true;
			}

			result = double.NaN;
			return false;
		}

19 View Source File : PropertyValidation.cs
License : MIT License
Project Creator : actions

public static void ValidatePropertyValue(String propertyName, Object value)
        {
            // Keep this consistent with XmlPropertyWriter.Write.
            if (null != value)
            {
                Type type = value.GetType();
                TypeCode typeCode = Type.GetTypeCode(type);

                if (type.IsEnum)
                {
                    ValidateStringValue(propertyName, ((Enum)value).ToString("D"));
                }
                else if (typeCode == TypeCode.Object && value is byte[])
                {
                    ValidateByteArray(propertyName, (byte[])value);
                }
                else if (typeCode == TypeCode.Object && value is Guid)
                {
                    //treat Guid like the other valid primitive types that
                    //don't have explicit columns, e.g. it gets stored as a string
                    ValidateStringValue(propertyName, ((Guid)value).ToString("N"));
                }
                else if (typeCode == TypeCode.Object)
                {
                    throw new PropertyTypeNotSupportedException(propertyName, type);
                }
                else if (typeCode == TypeCode.DBNull)
                {
                    throw new PropertyTypeNotSupportedException(propertyName, type);
                }
                else if (typeCode == TypeCode.Empty)
                {
                    // should be impossible with null check above, but just in case.
                    throw new PropertyTypeNotSupportedException(propertyName, type);
                }
                else if (typeCode == TypeCode.Int32)
                {
                    ValidateInt32(propertyName, (int)value);
                }
                else if (typeCode == TypeCode.Double)
                {
                    ValidateDouble(propertyName, (double)value);
                }
                else if (typeCode == TypeCode.DateTime)
                {
                    ValidateDateTime(propertyName, (DateTime)value);
                }
                else if (typeCode == TypeCode.String)
                {
                    ValidateStringValue(propertyName, (String)value);
                }
                else
                {
                    // Here are the remaining types. All are supported over in DbArtifactPropertyValueColumns.
                    // With a property definition they'll be strongly-typed when they're read back.
                    // Otherwise they read back as strings.
                    //   Boolean
                    //   Char
                    //   SByte
                    //   Byte
                    //   Int16
                    //   UInt16
                    //   UInt32
                    //   Int64
                    //   UInt64
                    //   Single
                    //   Decimal
                    ValidateStringValue(propertyName, value.ToString());
                }
            }
        }

19 View Source File : TypeFuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz

private T InstantiateAndFuzzViaPropertiesWhenTheyHaveSetters<T>(ConstructorInfo constructor, int recursionLevel,
            Type genericType, object instance = null)
        {
            if (instance == null)
            {
                instance = constructor.Invoke(new object[0]);
            }

            var propertyInfos = genericType.GetProperties().Where(prop => prop.CanWrite);
            foreach (var propertyInfo in propertyInfos)
            {
                var propertyType = propertyInfo.PropertyType;
                var propertyValue = FuzzAnyDotNetType(Type.GetTypeCode(propertyType), propertyType, recursionLevel);

                propertyInfo.SetValue(instance, propertyValue);
            }

            return (T)instance;
        }

19 View Source File : Protocol16Serializer.cs
License : MIT License
Project Creator : 0blu

private static Protocol16Type TypeCodeToProtocol16Type(Type type)
        {
            switch (Type.GetTypeCode(type))
            {
                case TypeCode.Boolean:
                    return Protocol16Type.Boolean;
                case TypeCode.Byte:
                    return Protocol16Type.Byte;
                case TypeCode.Int16:
                    return Protocol16Type.Short;
                case TypeCode.Int32:
                    return Protocol16Type.Integer;
                case TypeCode.Int64:
                    return Protocol16Type.Long;
                case TypeCode.Single:
                    return Protocol16Type.Float;
                case TypeCode.Double:
                    return Protocol16Type.Double;
                case TypeCode.String:
                    return Protocol16Type.String;
            }

            if (type.IsArray)
            {
                var elementType = type.GetElementType();
                
                if (elementType == typeof(byte))
                {
                    return Protocol16Type.ByteArray;
                }

                if (elementType == typeof(string))
                {
                    return Protocol16Type.StringArray;
                }

                if (elementType == typeof(int))
                {
                    return Protocol16Type.IntegerArray;
                }

                if (elementType == typeof(object))
                {
                    return Protocol16Type.ObjectArray;
                }

                return Protocol16Type.Array;
            }

            if (type == typeof(Hashtable))
            {
                return Protocol16Type.Hashtable;
            }

            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>))
            {
                return Protocol16Type.Dictionary;
            }

            if (type == typeof(EventData))
            {
                return Protocol16Type.EventData;
            }

            if (type == typeof(OperationRequest))
            {
                return Protocol16Type.OperationRequest;
            }

            if (type == typeof(OperationResponse))
            {
                return Protocol16Type.OperationResponse;
            }

            return Protocol16Type.Unknown;
        }

19 View Source File : MySqlDbAdapter.cs
License : MIT License
Project Creator : 17MKH

public override void ResolveColumn(IColumnDescriptor columnDescriptor)
    {
        var propertyType = columnDescriptor.PropertyInfo.PropertyType;
        var isNullable = propertyType.IsNullable();
        if (isNullable)
        {
            propertyType = Nullable.GetUnderlyingType(propertyType);
            if (propertyType == null)
                throw new Exception("Property2Column error");
        }

        if (propertyType.IsEnum)
        {
            if (!isNullable)
            {
                columnDescriptor.DefaultValue = "0";
            }

            columnDescriptor.TypeName = "SMALLINT";
            return;
        }

        if (propertyType.IsGuid())
        {
            columnDescriptor.TypeName = "CHAR";
            columnDescriptor.Length = 36;
            return;
        }

        var typeCode = Type.GetTypeCode(propertyType);
        switch (typeCode)
        {
            case TypeCode.Char:
                columnDescriptor.TypeName = "CHAR";
                break;
            case TypeCode.String:
                columnDescriptor.TypeName = columnDescriptor.Length < 1 ? "TEXT" : "VARCHAR";
                break;
            case TypeCode.Boolean:
                if (!isNullable)
                {
                    columnDescriptor.DefaultValue = "b'0'";
                }

                columnDescriptor.TypeName = "BIT";
                break;
            case TypeCode.Byte:
                if (!isNullable)
                {
                    columnDescriptor.DefaultValue = "0";
                }
                columnDescriptor.TypeName = "TINYINT";
                break;
            case TypeCode.Int16:
            case TypeCode.Int32:
                if (!isNullable)
                {
                    columnDescriptor.DefaultValue = "0";
                }

                columnDescriptor.TypeName = "INT";
                break;
            case TypeCode.Int64:
                if (!isNullable)
                {
                    columnDescriptor.DefaultValue = "0";
                }

                columnDescriptor.TypeName = "BIGINT";
                break;
            case TypeCode.DateTime:
                if (!isNullable)
                {
                    columnDescriptor.DefaultValue = "CURRENT_TIMESTAMP";
                }
                columnDescriptor.TypeName = "DATETIME";
                break;
            case TypeCode.Decimal:
                if (!isNullable)
                {
                    columnDescriptor.DefaultValue = "0";
                }

                columnDescriptor.TypeName = "DECIMAL";
                break;
            case TypeCode.Double:
                if (!isNullable)
                {
                    columnDescriptor.DefaultValue = "0";
                }

                columnDescriptor.TypeName = "DOUBLE";
                break;
            case TypeCode.Single:
                if (!isNullable)
                {
                    columnDescriptor.DefaultValue = "0";
                }

                columnDescriptor.TypeName = "FLOAT";
                break;
        }

        //主键默认值为null
        if (columnDescriptor.IsPrimaryKey)
        {
            columnDescriptor.DefaultValue = null;
        }
    }

19 View Source File : DefaultRedisSerializer.cs
License : MIT License
Project Creator : 17MKH

private bool IsNotBaseType<T>()
    {
        return Type.GetTypeCode(typeof(T)) == TypeCode.Object;
    }

19 View Source File : ReaderCache.cs
License : Apache License 2.0
Project Creator : aadreja

private static void ConvertValueToEnum(ILGenerator il, Type from, Type to, Type via)
        {
            MethodInfo op;
            if (from == (via ?? to))
            {
                il.Emit(OpCodes.Unbox_Any, to); // stack is now [target][target][typed-value]
            }
            else if ((op = GetOperator(from, to)) != null)
            {
                // this is handy for things like decimal <===> double
                il.Emit(OpCodes.Unbox_Any, from); // stack is now [target][target][data-typed-value]
                il.Emit(OpCodes.Call, op); // stack is now [target][target][typed-value]
            }
            else
            {
                bool handled = false;
                OpCode opCode = default;
                switch (Type.GetTypeCode(from))
                {
                    case TypeCode.Boolean:
                    case TypeCode.Byte:
                    case TypeCode.SByte:
                    case TypeCode.Int16:
                    case TypeCode.UInt16:
                    case TypeCode.Int32:
                    case TypeCode.UInt32:
                    case TypeCode.Int64:
                    case TypeCode.UInt64:
                    case TypeCode.Single:
                    case TypeCode.Double:
                        handled = true;
                        switch (Type.GetTypeCode(via ?? to))
                        {
                            case TypeCode.Byte:
                                opCode = OpCodes.Conv_Ovf_I1_Un; break;
                            case TypeCode.SByte:
                                opCode = OpCodes.Conv_Ovf_I1; break;
                            case TypeCode.UInt16:
                                opCode = OpCodes.Conv_Ovf_I2_Un; break;
                            case TypeCode.Int16:
                                opCode = OpCodes.Conv_Ovf_I2; break;
                            case TypeCode.UInt32:
                                opCode = OpCodes.Conv_Ovf_I4_Un; break;
                            case TypeCode.Boolean: // boolean is basically an int, at least at this level
                            case TypeCode.Int32:
                                opCode = OpCodes.Conv_Ovf_I4; break;
                            case TypeCode.UInt64:
                                opCode = OpCodes.Conv_Ovf_I8_Un; break;
                            case TypeCode.Int64:
                                opCode = OpCodes.Conv_Ovf_I8; break;
                            case TypeCode.Single:
                                opCode = OpCodes.Conv_R4; break;
                            case TypeCode.Double:
                                opCode = OpCodes.Conv_R8; break;
                            default:
                                handled = false;
                                break;
                        }
                        break;
                }
                if (handled)
                {
                    il.Emit(OpCodes.Unbox_Any, from); // stack is now [target][target][col-typed-value]
                    il.Emit(opCode); // stack is now [target][target][typed-value]
                    if (to == typeof(bool))
                    { // compare to zero; I checked "csc" - this is the trick it uses; nice
                        il.Emit(OpCodes.Ldc_I4_0);
                        il.Emit(OpCodes.Ceq);
                        il.Emit(OpCodes.Ldc_I4_0);
                        il.Emit(OpCodes.Ceq);
                    }
                }
                else
                {
                    il.Emit(OpCodes.Ldtoken, via ?? to); // stack is now [target][target][value][member-type-token]
                    il.EmitCall(OpCodes.Call, typeof(Type).GetMethod(nameof(Type.GetTypeFromHandle)), null); // stack is now [target][target][value][member-type]
                    il.EmitCall(OpCodes.Call, typeof(Convert).GetMethod(nameof(Convert.ChangeType), new Type[] { typeof(object), typeof(Type) }), null); // stack is now [target][target][boxed-member-type-value]
                    il.Emit(OpCodes.Unbox_Any, to); // stack is now [target][target][typed-value]
                }
            }
        }

19 View Source File : Stfld.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

public unsafe void Load(DarksVMContext ctx, out ExecutionState state)
        {
            var sp = ctx.Registers[DarksVMConstants.REG_SP].U4;
            var fieldSlot = ctx.Stack[sp--];
            var valSlot = ctx.Stack[sp--];
            var objSlot = ctx.Stack[sp--];

            var field = (FieldInfo) ctx.Instance.Data.LookupReference(fieldSlot.U4);
            if(!field.IsStatic && objSlot.O == null)
                throw new NullReferenceException();

            object value;
            if(Type.GetTypeCode(field.FieldType) == TypeCode.String && valSlot.O == null)
                value = ctx.Instance.Data.LookupString(valSlot.U4);
            else
                value = valSlot.ToObject(field.FieldType);

            if(field.DeclaringType.IsValueType && objSlot.O is IReference)
            {
                TypedReference typedRef;
                ((IReference) objSlot.O).ToTypedReference(ctx, &typedRef, field.DeclaringType);
                TypedReferenceHelpers.CastTypedRef(&typedRef, field.DeclaringType);
                field.SetValueDirect(typedRef, value);
            }
            else
            {
                field.SetValue(objSlot.ToObject(field.DeclaringType), value);
            }

            ctx.Stack.SetTopPosition(sp);
            ctx.Registers[DarksVMConstants.REG_SP].U4 = sp;
            state = ExecutionState.Next;
        }

See More Examples