Пример #1
0
    /// <summary>
    /// 将枚举转为数字值
    /// </summary>
    public static string _ToEnumInteger(this object enumValue, System.Type e)
    {
        switch (e.GetEnumUnderlyingType().Name)
        {
        case "Byte":
            return(Convert.ToByte(enumValue).ToString());

        case "SByte":
            return(Convert.ToSByte(enumValue).ToString());

        case "UInt16":
            return(Convert.ToUInt16(enumValue).ToString());

        case "Int16":
            return(Convert.ToInt16(enumValue).ToString());

        case "UInt32":
            return(Convert.ToUInt32(enumValue).ToString());

        case "Int32":
            return(Convert.ToInt32(enumValue).ToString());

        case "UInt64":
            return(Convert.ToUInt64(enumValue).ToString());

        case "Int64":
            return(Convert.ToInt64(enumValue).ToString());
        }
        throw new Exception("unknown Underlying Type");
    }
Пример #2
0
 public EnumConfiguration(Type enumType)
 {
     _signed = IsSignedEnum(enumType);
     _flags = IsFlagsEnum(enumType);
     _names = enumType.GetEnumNames();
     var members = enumType.GetMembers(BindingFlags.Static | BindingFlags.Public);
     Debug.Assert(members.Length == _names.Length);
     for (int i = 0; i < members.Length; i++)
     {
         var a = members[i].GetCustomAttributes<PersistedNameAttribute>().FirstOrDefault();
         if (a != null) _names[i] = a.Name;
     }
     var undertype = enumType.GetEnumUnderlyingType();
     var enumValues = enumType.GetEnumValues();
     IEnumerable<ulong> enumValuesUlongs;
     if (undertype == typeof(int)) enumValuesUlongs = enumValues.Cast<int>().Select(i => (ulong)i);
     else if (undertype == typeof(uint)) enumValuesUlongs = enumValues.Cast<uint>().Select(i => (ulong)i);
     else if (undertype == typeof(sbyte)) enumValuesUlongs = enumValues.Cast<sbyte>().Select(i => (ulong)i);
     else if (undertype == typeof(byte)) enumValuesUlongs = enumValues.Cast<byte>().Select(i => (ulong)i);
     else if (undertype == typeof(short)) enumValuesUlongs = enumValues.Cast<short>().Select(i => (ulong)i);
     else if (undertype == typeof(ushort)) enumValuesUlongs = enumValues.Cast<ushort>().Select(i => (ulong)i);
     else if (undertype == typeof(long)) enumValuesUlongs = enumValues.Cast<long>().Select(i => (ulong)i);
     else enumValuesUlongs = enumValues.Cast<ulong>();
     _values = enumValuesUlongs.ToArray();
 }
	private void GenerateEnumTypeDeclaration(Type enumType)
	{
		DataContractAttribute dataContractAttr = (DataContractAttribute)Attribute.GetCustomAttribute(enumType, typeof(DataContractAttribute));
        if (dataContractAttr != null)
        {
			this.GenerateDataContractAttribute(enumType);
		}
		
		if (enumType.GetCustomAttributes(typeof(FlagsAttribute), false).Length > 0)
        {

this.Write("[System.Flags]\r\n");


		}
		
		
this.Write("public enum ");

this.Write(this.ToStringHelper.ToStringWithCulture(CodeGenUtilities.GetSafeName(enumType.Name)));


		
		Type underlyingType = enumType.GetEnumUnderlyingType();
        if (underlyingType != typeof(int))
		{
			
this.Write(" : ");

this.Write(this.ToStringHelper.ToStringWithCulture(CodeGenUtilities.GetTypeName(underlyingType)));


		}
	}
        public override string ToQuotedString(Type fieldType, object value)
        {
            if (fieldType.HasAttribute<EnumAsIntAttribute>())
            {
                return this.ConvertNumber(fieldType.GetEnumUnderlyingType(), value).ToString();
            }

            if (value is int && !fieldType.IsEnumFlags())
            {
                value = fieldType.GetEnumName(value);
            }

            if (fieldType.IsEnum)
            {
                var enumValue = DialectProvider.StringSerializer.SerializeToString(value);
                // Oracle stores empty strings in varchar columns as null so match that behavior here
                if (enumValue == null)
                    return null;
                enumValue = DialectProvider.GetQuotedValue(enumValue.Trim('"'));
                return enumValue == "''"
                    ? "null"
                    : enumValue;
            }
            return base.ToQuotedString(fieldType, value);
        }
Пример #5
0
 Action<IILGen> GenerateEnum2EnumConversion(Type from, Type to)
 {
     var fromcfg = new EnumFieldHandler.EnumConfiguration(from);
     var tocfg = new EnumFieldHandler.EnumConfiguration(to);
     if (fromcfg.IsSubsetOf(tocfg))
     {
         return GenerateConversion(from.GetEnumUnderlyingType(), to.GetEnumUnderlyingType());
     }
     return null;
 }
Пример #6
0
        public virtual bool IsEnumDefined(object value)
        {
            ArgumentNullException.ThrowIfNull(value);

            if (!IsEnum)
            {
                throw new ArgumentException(SR.Arg_MustBeEnum, nameof(value));
            }

            // Check if both of them are of the same type
            Type valueType = value.GetType();

            // If the value is an Enum then we need to extract the underlying value from it
            if (valueType.IsEnum)
            {
                if (!valueType.IsEquivalentTo(this))
                {
                    throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, valueType, this));
                }

                valueType = valueType.GetEnumUnderlyingType();
            }

            // If a string is passed in
            if (valueType == typeof(string))
            {
                string[] names = GetEnumNames();
                if (Array.IndexOf(names, value) >= 0)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }

            // If an enum or integer value is passed in
            if (Type.IsIntegerType(valueType))
            {
                Type underlyingType = GetEnumUnderlyingType();
                // We cannot compare the types directly because valueType is always a runtime type but underlyingType might not be.
                if (underlyingType.GetTypeCodeImpl() != valueType.GetTypeCodeImpl())
                {
                    throw new ArgumentException(SR.Format(SR.Arg_EnumUnderlyingTypeAndObjectMustBeSameType, valueType, underlyingType));
                }

                Array values = GetEnumRawConstantValues();
                return(BinarySearch(values, value) >= 0);
            }
            else
            {
                throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
            }
        }
Пример #7
0
        protected Expression GetConvertedValue(Type targetType)
        {
            var value = ExtendedProperties.GetExtendedProperty("value") ?? String.Empty;

            if (targetType.IsEnum)
                return Expression.Constant(((IConvertible)Enum.Parse(targetType, value, true)).ToType(targetType.GetEnumUnderlyingType(), CultureInfo.InvariantCulture));

            return typeof(IConvertible).IsAssignableFrom(targetType)
                        ? Expression.Constant(((IConvertible)value).ToType(targetType, CultureInfo.InvariantCulture))
                        : Expression.Convert(Expression.Constant(value), targetType) as Expression;
        }
 public static UIAutomationType TypeToAutomationType(Type type)
 {
     if (IsElementOnServerSide(type))
         return UIAutomationType.UIAutomationType_Element;
     if (type.IsEnum && type.GetEnumUnderlyingType() == typeof(int))
         type = typeof(int);
     UIAutomationType res;
     if (_typeMapping.TryGetValue(type, out res))
         return res;
     throw new NotSupportedException("Provided type is not supported");
 }
Пример #9
0
        public static Type GetUnderlyingType(Type enumType)
        {
            if (enumType == null)
            {
                throw new ArgumentNullException("enumType");
            }
            Contract.Ensures(Contract.Result <Type>() != null);
            Contract.EndContractBlock();

            return(enumType.GetEnumUnderlyingType());
        }
Пример #10
0
 /// <summary>
 /// 确定当前实例是否是继承或者实现某个Type
 /// </summary>
 /// <param name="type"></param>
 /// <returns></returns>
 public static bool IsInheritOfType(this Type self, Type type)
 {
     if (type.IsInterface)
     {
         return(self.GetInterface(type.Name) != null);
     }
     if (type.IsEnum)
     {
         return(self.GetEnumUnderlyingType() == type);
     }
     return(self.IsSubclassOf(type));
 }
Пример #11
0
        /// <summary>
        /// </summary>
        /// <param name="fileName">
        /// </param>
        /// <param name="enumName">
        /// </param>
        /// <param name="enumType">
        /// </param>
        /// <param name="writeValues">
        /// </param>
        public static void WriteEnumList(string fileName, string enumName, Type enumType, bool writeValues = true)
        {
            bool isFlagsEnum = false;
            object[] memInfo = enumType.GetCustomAttributes(typeof(FlagsAttribute), false);
            isFlagsEnum = memInfo.Length > 0;

            TextWriter tw = new StreamWriter(fileName);

            WriteHeader1(tw, enumName);
            WriteCode(tw, enumType.FullName);
            if (writeValues)
            {
                tw.Write(" : ");
                WriteCode(tw, enumType.GetEnumUnderlyingType().Name);
            }

            if (isFlagsEnum)
            {
                tw.WriteLine();
                tw.WriteLine();
                WriteCode(tw, "[Flags]");
            }

            tw.WriteLine();
            WriteHorizonalLine(tw);
            tw.WriteLine();
            Array temp2 = Enum.GetValues(enumType);

            int max = temp2.Length;
            foreach (object v in temp2)
            {
                string eName = Enum.GetName(enumType, v);
                tw.Write("**" + eName + "**");
                if (writeValues)
                {
                    object underlyingValue = Convert.ChangeType(v, Enum.GetUnderlyingType(v.GetType()));
                    tw.Write(" = " + underlyingValue);
                }

                max--;
                if (max > 0)
                {
                    tw.WriteLine(",");
                }

                tw.WriteLine();
            }

            WriteFooter(tw);
            tw.Close();
        }
        public Enum ReadEnum(Type enumType, ByteOrder byteOrder)
        {
            Require.NotNull(enumType, "enumType");
            Require.That("enumType", enumType.IsEnum);

            var enumBaseType = enumType.GetEnumUnderlyingType();
            if (enumBaseType == typeof(byte))
            {
                var value = ReadByte();
                return (Enum)Enum.ToObject(enumType, value);
            }
            if (enumBaseType == typeof(sbyte))
            {
                var value = ReadSByte();
                return (Enum)Enum.ToObject(enumType, value);
            }
            if(enumBaseType == typeof(int))
            {
                var value = ReadInt32(byteOrder);
                return (Enum)Enum.ToObject(enumType, value);
            }
            if (enumBaseType == typeof(uint))
            {
                var value = ReadUInt32(byteOrder);
                return (Enum)Enum.ToObject(enumType, value);
            }
            if (enumBaseType == typeof(short))
            {
                var value = ReadInt16(byteOrder);
                return (Enum)Enum.ToObject(enumType, value);
            }
            if (enumBaseType == typeof(ushort))
            {
                var value = ReadUInt16(byteOrder);
                return (Enum)Enum.ToObject(enumType, value);
            }
            if (enumBaseType == typeof(long))
            {
                var value = ReadInt64(byteOrder);
                return (Enum)Enum.ToObject(enumType, value);
            }
            if (enumBaseType == typeof(ulong))
            {
                var value = ReadUInt64(byteOrder);
                return (Enum)Enum.ToObject(enumType, value);
            }
            throw new ArgumentOutOfRangeException("enumType", "The provided argument did not meet the specified requirements.");
        }
Пример #13
0
        public static void EmitLdDefaultValue(this ILGenerator gen, Type returnType)
        {
            if (returnType.IsEnum)
                returnType = returnType.GetEnumUnderlyingType();

            if (returnType==typeof(void)) {}
            else if (returnType.IsClass || returnType.IsInterface)
            {
                gen.Emit(OpCodes.Ldnull);
            }
            else if (I4CompatibleTypes.Contains(returnType))
            {
                gen.Emit(OpCodes.Ldc_I4_0);
            }
            else if (returnType==typeof(double))
            {
                gen.Emit(OpCodes.Ldc_R8, 0.0);
            }
            else if (returnType==typeof(float))
            {
                gen.Emit(OpCodes.Ldc_R4, 0.0f);
            }
            else if (returnType==typeof(long) || returnType==typeof(ulong))
            {
                gen.Emit(OpCodes.Ldc_I8, 0L);
            }
            else if (returnType==typeof(decimal))
            {
                var consDecimal = typeof(decimal).GetConstructor(new[] {typeof(int)});
                gen.Emit(OpCodes.Ldc_I4_0);
                gen.Emit(OpCodes.Newobj, consDecimal);
            }
            else if (returnType.IsValueType)
            {
                var returnTypeLocal = gen.DeclareLocal(returnType);
                gen.Emit(OpCodes.Ldloca, returnTypeLocal);
                gen.Emit(OpCodes.Initobj, returnType);
                gen.Emit(OpCodes.Ldloc, returnTypeLocal);
            }
            else
            {
                throw new InvalidOperationException("Unable to handle return type");
            }
        }
Пример #14
0
 public EnumTypeDescriptor(ITypeDescriptorCallbacks typeSerializers, Type type)
 {
     _typeSerializers = typeSerializers;
     _type = type;
     _name = typeSerializers.TypeNameMapper.ToName(type);
     _signed = IsSignedEnum(type);
     _flags = IsFlagsEnum(type);
     var undertype = type.GetEnumUnderlyingType();
     var enumValues = type.GetEnumValues();
     IEnumerable<ulong> enumValuesUlongs;
     if (undertype == typeof(int)) enumValuesUlongs = enumValues.Cast<int>().Select(i => (ulong)i);
     else if (undertype == typeof(uint)) enumValuesUlongs = enumValues.Cast<uint>().Select(i => (ulong)i);
     else if (undertype == typeof(sbyte)) enumValuesUlongs = enumValues.Cast<sbyte>().Select(i => (ulong)i);
     else if (undertype == typeof(byte)) enumValuesUlongs = enumValues.Cast<byte>().Select(i => (ulong)i);
     else if (undertype == typeof(short)) enumValuesUlongs = enumValues.Cast<short>().Select(i => (ulong)i);
     else if (undertype == typeof(ushort)) enumValuesUlongs = enumValues.Cast<ushort>().Select(i => (ulong)i);
     else if (undertype == typeof(long)) enumValuesUlongs = enumValues.Cast<long>().Select(i => (ulong)i);
     else enumValuesUlongs = enumValues.Cast<ulong>();
     _pairs = type.GetEnumNames().Zip(enumValuesUlongs.ToArray(), (s, v) => new KeyValuePair<string, ulong>(s, v)).ToList();
 }
        public override string ToQuotedString(Type fieldType, object value)
        {
            var isEnumAsInt = fieldType.HasAttribute<EnumAsIntAttribute>();
            if (isEnumAsInt)
                return this.ConvertNumber(fieldType.GetEnumUnderlyingType(), 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;
        }
Пример #16
0
		/// <summary>
		/// Reads a primitive value of the specified type.
		/// Stack transition: ... => ..., value
		/// </summary>
		void ReadPrimitiveValue(ILGenerator il, LocalBuilder reader, Type fieldType)
		{
			if (fieldType.IsEnum) {
				fieldType = fieldType.GetEnumUnderlyingType();
				Debug.Assert(fieldType.IsPrimitive);
			}
			il.Emit(OpCodes.Ldloc, reader);
			switch (Type.GetTypeCode(fieldType)) {
				case TypeCode.Boolean:
				case TypeCode.SByte:
				case TypeCode.Byte:
					il.Emit(callVirt, readByte);
					break;
				case TypeCode.Char:
				case TypeCode.Int16:
				case TypeCode.UInt16:
					il.Emit(callVirt, readShort);
					break;
				case TypeCode.Int32:
				case TypeCode.UInt32:
					il.Emit(callVirt, readInt);
					break;
				case TypeCode.Int64:
				case TypeCode.UInt64:
					il.Emit(callVirt, readLong);
					break;
				case TypeCode.Single:
					il.Emit(callVirt, readFloat);
					break;
				case TypeCode.Double:
					il.Emit(callVirt, readDouble);
					break;
				default:
					throw new NotSupportedException("Unknown primitive type " + fieldType);
			}
		}
Пример #17
0
		ObjectReader CreateReader(Type type)
		{
			if (type == typeof(string)) {
				// String contents are written in the object creation section,
				// not into the field value section; so there's nothing to read here.
				return delegate {};
			}
			bool isArray = type.IsArray;
			if (isArray) {
				if (type.GetArrayRank() != 1)
					throw new NotSupportedException();
				type = type.GetElementType();
				if (!type.IsValueType) {
					return delegate (DeserializationContext context, object arrayInstance) {
						object[] array = (object[])arrayInstance;
						for (int i = 0; i < array.Length; i++) {
							array[i] = context.ReadObject();
						}
					};
				} else if (type == typeof(byte)) {
					return delegate (DeserializationContext context, object arrayInstance) {
						byte[] array = (byte[])arrayInstance;
						BinaryReader binaryReader = context.Reader;
						int pos = 0;
						int bytesRead;
						do {
							bytesRead = binaryReader.Read(array, pos, array.Length - pos);
							pos += bytesRead;
						} while (bytesRead > 0);
						if (pos != array.Length)
							throw new EndOfStreamException();
					};
				}
			}
			var fields = GetSerializableFields(type);
			if (fields.Count == 0) {
				// The reader has nothing to do for this object.
				return delegate { };
			}
			
			DynamicMethod dynamicMethod = new DynamicMethod(
				(isArray ? "ReadArray_" : "Read_") + type.Name,
				MethodAttributes.Public | MethodAttributes.Static,
				CallingConventions.Standard,
				typeof(void), new [] { typeof(DeserializationContext), typeof(object) },
				type,
				true);
			ILGenerator il = dynamicMethod.GetILGenerator();
			
			var reader = il.DeclareLocal(typeof(BinaryReader));
			
			il.Emit(OpCodes.Ldarg_0);
			il.Emit(OpCodes.Ldfld, readerField);
			il.Emit(OpCodes.Stloc, reader); // reader = context.reader;
			
			if (isArray) {
				var instance = il.DeclareLocal(type.MakeArrayType());
				il.Emit(OpCodes.Ldarg_1);
				il.Emit(OpCodes.Castclass, type.MakeArrayType());
				il.Emit(OpCodes.Stloc, instance); // instance = (type[])arg_1;
				
				// for (int i = 0; i < instance.Length; i++) read &instance[i];
				
				var loopStart = il.DefineLabel();
				var loopHead = il.DefineLabel();
				var loopVariable = il.DeclareLocal(typeof(int));
				il.Emit(OpCodes.Ldc_I4_0);
				il.Emit(OpCodes.Stloc, loopVariable); // loopVariable = 0
				il.Emit(OpCodes.Br, loopHead); // goto loopHead;
				
				il.MarkLabel(loopStart);
				
				if (type.IsEnum || type.IsPrimitive) {
					if (type.IsEnum) {
						type = type.GetEnumUnderlyingType();
					}
					Debug.Assert(type.IsPrimitive);
					il.Emit(OpCodes.Ldloc, instance); // instance
					il.Emit(OpCodes.Ldloc, loopVariable); // instance, loopVariable
					ReadPrimitiveValue(il, reader, type); // instance, loopVariable, value
					switch (Type.GetTypeCode(type)) {
						case TypeCode.Boolean:
						case TypeCode.SByte:
						case TypeCode.Byte:
							il.Emit(OpCodes.Stelem_I1); // instance[loopVariable] = value;
							break;
						case TypeCode.Char:
						case TypeCode.Int16:
						case TypeCode.UInt16:
							il.Emit(OpCodes.Stelem_I2); // instance[loopVariable] = value;
							break;
						case TypeCode.Int32:
						case TypeCode.UInt32:
							il.Emit(OpCodes.Stelem_I4); // instance[loopVariable] = value;
							break;
						case TypeCode.Int64:
						case TypeCode.UInt64:
							il.Emit(OpCodes.Stelem_I8); // instance[loopVariable] = value;
							break;
						case TypeCode.Single:
							il.Emit(OpCodes.Stelem_R4); // instance[loopVariable] = value;
							break;
						case TypeCode.Double:
							il.Emit(OpCodes.Stelem_R8); // instance[loopVariable] = value;
							break;
						default:
							throw new NotSupportedException("Unknown primitive type " + type);
					}
				} else {
					il.Emit(OpCodes.Ldloc, instance); // instance
					il.Emit(OpCodes.Ldloc, loopVariable); // instance, loopVariable
					il.Emit(OpCodes.Ldelema, type); // instance[loopVariable]
					EmitReadValueType(il, reader, type);
				}
				
				il.Emit(OpCodes.Ldloc, loopVariable); // loopVariable
				il.Emit(OpCodes.Ldc_I4_1); // loopVariable, 1
				il.Emit(OpCodes.Add); // loopVariable+1
				il.Emit(OpCodes.Stloc, loopVariable); // loopVariable++;
				
				il.MarkLabel(loopHead);
				il.Emit(OpCodes.Ldloc, loopVariable); // loopVariable
				il.Emit(OpCodes.Ldloc, instance); // loopVariable, instance
				il.Emit(OpCodes.Ldlen); // loopVariable, instance.Length
				il.Emit(OpCodes.Conv_I4);
				il.Emit(OpCodes.Blt, loopStart); // if (loopVariable < instance.Length) goto loopStart;
			} else if (type.IsValueType) {
				// boxed value type
				il.Emit(OpCodes.Ldarg_1); // instance
				il.Emit(OpCodes.Unbox, type); // &(Type)instance
				if (type.IsEnum || type.IsPrimitive) {
					if (type.IsEnum) {
						type = type.GetEnumUnderlyingType();
					}
					Debug.Assert(type.IsPrimitive);
					ReadPrimitiveValue(il, reader, type); // &(Type)instance, value
					switch (Type.GetTypeCode(type)) {
						case TypeCode.Boolean:
						case TypeCode.SByte:
						case TypeCode.Byte:
							il.Emit(OpCodes.Stind_I1);
							break;
						case TypeCode.Char:
						case TypeCode.Int16:
						case TypeCode.UInt16:
							il.Emit(OpCodes.Stind_I2);
							break;
						case TypeCode.Int32:
						case TypeCode.UInt32:
							il.Emit(OpCodes.Stind_I4);
							break;
						case TypeCode.Int64:
						case TypeCode.UInt64:
							il.Emit(OpCodes.Stind_I8);
							break;
						case TypeCode.Single:
							il.Emit(OpCodes.Stind_R4);
							break;
						case TypeCode.Double:
							il.Emit(OpCodes.Stind_R8);
							break;
						default:
							throw new NotSupportedException("Unknown primitive type " + type);
					}
				} else {
					EmitReadValueType(il, reader, type);
				}
			} else {
				// reference type
				var instance = il.DeclareLocal(type);
				il.Emit(OpCodes.Ldarg_1);
				il.Emit(OpCodes.Castclass, type);
				il.Emit(OpCodes.Stloc, instance); // instance = (type)arg_1;
				
				foreach (FieldInfo field in fields) {
					EmitReadField(il, reader, instance, field); // read instance.Field
				}
			}
			il.Emit(OpCodes.Ret);
			return (ObjectReader)dynamicMethod.CreateDelegate(typeof(ObjectReader));
		}
 private static bool EqualTypes(Type parameterType, Type payloadType)
 {
     return parameterType.IsEnum && !payloadType.IsEnum ?
         parameterType.GetEnumUnderlyingType() == payloadType :
         parameterType == payloadType;
 }
Пример #19
0
        private static (object?, InvalidOperationException?) TryConvertObject(string context, object?val, Type targetType)
        {
            var targetIsNullable = targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(Nullable <>);

            // Note: 'null's can enter the system as the representation of an 'unknown' value.
            // Before calling 'Convert' we will have already lifted the 'IsKnown' bit out, but we
            // will be passing null around as a value.
            if (val == null)
            {
                if (targetIsNullable)
                {
                    // A 'null' value coerces to a nullable null.
                    return(null, null);
                }

                if (targetType.IsValueType)
                {
                    return(Activator.CreateInstance(targetType), null);
                }

                // for all other types, can just return the null value right back out as a legal
                // reference type value.
                return(null, null);
            }

            // We're not null and we're converting to Nullable<T>, just convert our value to be a T.
            if (targetIsNullable)
            {
                return(TryConvertObject(context, val, targetType.GenericTypeArguments.Single()));
            }

            if (targetType == typeof(string))
            {
                return(TryEnsureType <string>(context, val));
            }

            if (targetType == typeof(bool))
            {
                return(TryEnsureType <bool>(context, val));
            }

            if (targetType == typeof(double))
            {
                return(TryEnsureType <double>(context, val));
            }

            if (targetType == typeof(int))
            {
                var(d, exception) = TryEnsureType <double>(context, val);
                if (exception != null)
                {
                    return(null, exception);
                }

                return((int)d, exception);
            }

            if (targetType == typeof(object))
            {
                return(val, null);
            }

            if (targetType == typeof(Asset))
            {
                return(TryEnsureType <Asset>(context, val));
            }

            if (targetType == typeof(Archive))
            {
                return(TryEnsureType <Archive>(context, val));
            }

            if (targetType == typeof(AssetOrArchive))
            {
                return(TryEnsureType <AssetOrArchive>(context, val));
            }

            if (targetType == typeof(JsonElement))
            {
                return(TryConvertJsonElement(context, val));
            }

            if (targetType.IsSubclassOf(typeof(Resource)) || targetType == typeof(Resource))
            {
                return(TryEnsureType <Resource>(context, val));
            }

            if (targetType.IsEnum)
            {
                var underlyingType = targetType.GetEnumUnderlyingType();
                var(value, exception) = TryConvertObject(context, val, underlyingType);
                if (exception != null || value is null)
                {
                    return(null, exception);
                }

                return(Enum.ToObject(targetType, value), null);
            }

            if (targetType.IsValueType && targetType.GetCustomAttribute <EnumTypeAttribute>() != null)
            {
                var valType = val.GetType();
                if (valType != typeof(string) &&
                    valType != typeof(double))
                {
                    return(null, new InvalidOperationException(
                               $"Expected {typeof(string).FullName} or {typeof(double).FullName} but got {valType.FullName} deserializing {context}"));
                }

                var enumTypeConstructor = targetType.GetConstructor(
                    BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { valType }, null);
                if (enumTypeConstructor == null)
                {
                    return(null, new InvalidOperationException(
                               $"Expected target type {targetType.FullName} to have a constructor with a single {valType.FullName} parameter."));
                }
                return(enumTypeConstructor.Invoke(new[] { val }), null);
            }

            if (targetType.IsConstructedGenericType)
            {
                if (targetType.GetGenericTypeDefinition() == typeof(Union <,>))
                {
                    return(TryConvertOneOf(context, val, targetType));
                }

                if (targetType.GetGenericTypeDefinition() == typeof(ImmutableArray <>))
                {
                    return(TryConvertArray(context, val, targetType));
                }

                if (targetType.GetGenericTypeDefinition() == typeof(ImmutableDictionary <,>))
                {
                    return(TryConvertDictionary(context, val, targetType));
                }

                throw new InvalidOperationException(
                          $"Unexpected generic target type {targetType.FullName} when deserializing {context}");
            }

            if (targetType.GetCustomAttribute <OutputTypeAttribute>() == null)
            {
                return(null, new InvalidOperationException(
                           $"Unexpected target type {targetType.FullName} when deserializing {context}"));
            }

            var constructor = GetPropertyConstructor(targetType);

            if (constructor == null)
            {
                return(null, new InvalidOperationException(
                           $"Expected target type {targetType.FullName} to have [{nameof(OutputConstructorAttribute)}] constructor when deserializing {context}"));
            }

            var(dictionary, tempException) = TryEnsureType <ImmutableDictionary <string, object> >(context, val);
            if (tempException != null)
            {
                return(null, tempException);
            }

            var constructorParameters = constructor.GetParameters();
            var arguments             = new object?[constructorParameters.Length];

            for (int i = 0, n = constructorParameters.Length; i < n; i++)
            {
                var parameter = constructorParameters[i];

                // Note: TryGetValue may not find a value here.  That can happen for things like
                // unknown vals.  That's ok.  We'll pass that through to 'Convert' and will get the
                // default value needed for the parameter type.
                dictionary !.TryGetValue(parameter.Name !, out var argValue);
                var(temp, tempException1) = TryConvertObject($"{targetType.FullName}({parameter.Name})", argValue, parameter.ParameterType);
                if (tempException1 != null)
                {
                    return(null, tempException1);
                }

                arguments[i] = temp;
            }

            return(constructor.Invoke(arguments), null);
        }
Пример #20
0
		void DisplayAsEnumMember(Type enumType)
		{
			object enumValue;
			try
			{
				enumValue = Convert.ChangeType(value, enumType.GetEnumUnderlyingType());
			}
			catch (OverflowException)
			{
				SetValueForDisplay(string.Format("{0} (not convertible to '{1}')", value, enumType.Name), value.ToString());
				return;
			}

			if (enumType.GetCustomAttribute<FlagsAttribute>() != null)
			{
				var allEnumFlags = Enum.GetValues(enumType)
					.Cast<object>().Select(x => (long)Convert.ChangeType(x, typeof(long))) // .Cast<long> fails to unbox int-backed enums
					.Aggregate(0L, (acc, val) => acc |= val);

				if ((~allEnumFlags & (long)Convert.ChangeType(enumValue, typeof(long))) > 0)
				{
					SetValueForDisplay(string.Format("{0} (not a valid combination of '{1}')", value, enumType.Name), value.ToString());
				}
				else
				{
					SetValueForDisplay(string.Format("{0:D} = {0:G}", Enum.ToObject(enumType, enumValue)));
				}
			}
			else
			{
				if (Enum.IsDefined(enumType, enumValue))
				{
					SetValueForDisplay(Enum.GetName(enumType, enumValue));
				}
				else
				{
					SetValueForDisplay(string.Format("{0} (not in '{1}')", value, enumType.Name), value.ToString());
				}
			}
		}
Пример #21
0
 public void GenerateLoad(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen> pushCtx, Action<IILGen> pushDescriptor, Type targetType)
 {
     pushReader(ilGenerator);
     Type typeRead;
     if (_signed)
     {
         ilGenerator.Call(() => default(AbstractBufferedReader).ReadVInt64());
         typeRead = typeof(long);
     }
     else
     {
         ilGenerator.Call(() => default(AbstractBufferedReader).ReadVUInt64());
         typeRead = typeof(ulong);
     }
     if (targetType == typeof(object))
     {
         ilGenerator.Do(pushDescriptor);
         if (_signed)
         {
             ilGenerator.Newobj(() => new DynamicEnum(0L, null));
         }
         else
         {
             ilGenerator.Newobj(() => new DynamicEnum(0UL, null));
         }
         ilGenerator.Castclass(typeof(object));
         return;
     }
     new DefaultTypeConvertorGenerator().GenerateConversion(typeRead, targetType.GetEnumUnderlyingType())(ilGenerator);
 }
	private void GenerateEnumMembers(Type enumType)
	{
		Type underlyingType = enumType.GetEnumUnderlyingType();
		string[] memberNames = Enum.GetNames(enumType);
        Type enumValueType = Enum.GetUnderlyingType(enumType);
        for (int i = 0; i < memberNames.Length; ++i)
        {
            string memberName = memberNames[i];
			FieldInfo fieldInfo = enumType.GetField(memberName);
			
			this.GenerateEnumMemberAttributes(fieldInfo);
			
			if(fieldInfo != null)
			{
				object memberValue = fieldInfo.GetRawConstantValue();
				
				object[] minMaxValues = null;
               	CodeGenUtilities.IntegralMinMaxValues.TryGetValue(underlyingType, out minMaxValues);				
			
				if (minMaxValues != null && !memberValue.Equals(minMaxValues[2]) && memberValue.Equals(minMaxValues[0]))
				{

this.Write(this.ToStringHelper.ToStringWithCulture(memberName));

this.Write(" = ");

this.Write(this.ToStringHelper.ToStringWithCulture(CodeGenUtilities.GetTypeName(underlyingType)));

this.Write(".MinValue ");


				}
				else if (minMaxValues != null && memberValue.Equals(minMaxValues[1]))
				{

this.Write(" \r\n");

this.Write(this.ToStringHelper.ToStringWithCulture(memberName));

this.Write(" = ");

this.Write(this.ToStringHelper.ToStringWithCulture(CodeGenUtilities.GetTypeName(underlyingType)));

this.Write(".MaxValue ");


				}
				else
				{

this.Write(" \r\n");

this.Write(this.ToStringHelper.ToStringWithCulture(memberName));

this.Write(" = ");

this.Write(this.ToStringHelper.ToStringWithCulture(memberValue.ToString()));

this.Write(" ");


				}
				
				if(i + 1 < memberNames.Length)
				{
					
this.Write(",");


				}
			}
		}			
	}
Пример #23
0
 /// <summary>
 /// Serializes a complex value.
 /// </summary>
 /// <param name="context">The serialization context to use.</param>
 /// <param name="tagStream">The stream to write completed blocks of tag data to.</param>
 /// <param name="block">The temporary block to write incomplete tag data to.</param>
 /// <param name="val">The value.</param>
 /// <param name="valueInfo">Information about the value. Can be <c>null</c>.</param>
 /// <param name="valueType">Type of the value.</param>
 private void SerializeComplexValue(ISerializationContext context, MemoryStream tagStream, IDataBlock block, object val, TagFieldAttribute valueInfo, Type valueType)
 {
     if (valueInfo != null && ((valueInfo.Flags & TagFieldFlags.Indirect) != 0 || valueType == typeof(ResourceReference)))
         SerializeIndirectValue(context, tagStream, block, val, valueType);
     else if (valueType.IsEnum)
         SerializePrimitiveValue(block.Writer, val, valueType.GetEnumUnderlyingType());
     else if (valueType == typeof(string))
         SerializeString(block.Writer, (string)val, valueInfo);
     else if (valueType == typeof(Tag))
         SerializeTag(block, (Tag)val);
     else if (valueType == typeof(TagInstance))
         SerializeTagReference(block.Writer, (TagInstance)val, valueInfo);
     else if (valueType == typeof(ResourceAddress))
         block.Writer.Write(((ResourceAddress)val).Value);
     else if (valueType == typeof(byte[]))
         SerializeDataReference(tagStream, block, (byte[])val, valueInfo);
     else if (valueType == typeof(Euler2))
         SerializeEulerAngles(block, (Euler2)val);
     else if (valueType == typeof(Euler3))
         SerializeEulerAngles(block, (Euler3)val);
     else if (valueType == typeof(Vector2))
         SerializeVector(block, (Vector2)val);
     else if (valueType == typeof(Vector3))
         SerializeVector(block, (Vector3)val);
     else if (valueType == typeof(Vector4))
         SerializeVector(block, (Vector4)val);
     else if (valueType == typeof(RealQuaternion))
         SerializeRealQuaternion(block, (RealQuaternion)val);
     else if (valueType == typeof(Matrix4x3))
         SerializeMatrix(block, (Matrix4x3)val);
     else if (valueType == typeof(StringID))
         block.Writer.Write(((StringID)val).Value);
     else if (valueType == typeof(Angle))
         block.Writer.Write(((Angle)val).Radians);
     else if (valueType.IsArray)
         SerializeInlineArray(context, tagStream, block, (Array)val, valueInfo);
     else if (valueType.IsGenericType && valueType.GetGenericTypeDefinition() == typeof(List<>))
         SerializeTagBlock(context, tagStream, block, val, valueType, valueInfo);
     else if (valueType.IsGenericType && valueType.GetGenericTypeDefinition() == typeof(Range<>))
         SerializeRange(block, val);
     else
         SerializeStruct(context, tagStream, block, new TagStructureInfo(val.GetType(), _version), val);
 }
Пример #24
0
        /// <summary>
        /// s[0] = value
        /// s[1] = reference to store value in
        /// </summary>
        /// <param name="gen">The code generator to use</param>
        /// <param name="type">The Type of the value</param>
        public static void EmitStoreToRef(this ILGenerator gen, Type type)
        {
            if (type.IsEnum)
                type = type.GetEnumUnderlyingType();

            if (type==typeof(byte) || type==typeof(sbyte))
            {
                gen.Emit(OpCodes.Stind_I1);
            }
            else if (type==typeof(short) || type==typeof(ushort))
            {
                gen.Emit(OpCodes.Stind_I2);
            }
            else if (type==typeof(int) || type==typeof(uint))
            {
                gen.Emit(OpCodes.Stind_I4);
            }
            else if (type==typeof(long) || type==typeof(ulong))
            {
                gen.Emit(OpCodes.Stind_I8);
            }
            else if (type==typeof(float))
            {
                gen.Emit(OpCodes.Stind_R4);
            }
            else if (type==typeof(double))
            {
                gen.Emit(OpCodes.Stind_R8);
            }
            else if (type.IsClass || type.IsInterface)
            {
                gen.Emit(OpCodes.Stind_Ref);
            }
            else if (type.IsValueType)
            {
                gen.Emit(OpCodes.Stobj, type);
            }
            else
            {
                throw new InvalidOperationException("Unable to handle type");
            }
        }
Пример #25
0
 public static bool IsCompatibleWith(Type type)
 {
     if (!type.IsEnum) return false;
     var enumUnderlyingType = type.GetEnumUnderlyingType();
     return SignedFieldHandler.IsCompatibleWith(enumUnderlyingType) || UnsignedFieldHandler.IsCompatibleWith(enumUnderlyingType);
 }
Пример #26
0
		ObjectWriter CreateWriter(Type type)
		{
			if (type == typeof(string)) {
				// String contents are written in the object creation section,
				// not into the field value section.
				return delegate {};
			}
			bool isArray = type.IsArray;
			if (isArray) {
				if (type.GetArrayRank() != 1)
					throw new NotSupportedException();
				type = type.GetElementType();
				if (!type.IsValueType) {
					return delegate (SerializationContext context, object array) {
						foreach (object val in (object[])array) {
							context.WriteObjectID(val);
						}
					};
				} else if (type == typeof(byte)) {
					return delegate (SerializationContext context, object array) {
						context.writer.Write((byte[])array);
					};
				}
			}
			List<FieldInfo> fields = GetSerializableFields(type);
			if (fields.Count == 0) {
				// The writer has nothing to do for this object.
				return delegate { };
			}
			
			
			DynamicMethod dynamicMethod = new DynamicMethod(
				(isArray ? "WriteArray_" : "Write_") + type.Name,
				typeof(void), new [] { typeof(SerializationContext), typeof(object) },
				true);
			ILGenerator il = dynamicMethod.GetILGenerator();
			
			var writer = il.DeclareLocal(typeof(BinaryWriter));
			
			il.Emit(OpCodes.Ldarg_0);
			il.Emit(OpCodes.Ldfld, writerField);
			il.Emit(OpCodes.Stloc, writer); // writer = context.writer;
			
			if (isArray) {
				var instance = il.DeclareLocal(type.MakeArrayType());
				il.Emit(OpCodes.Ldarg_1);
				il.Emit(OpCodes.Castclass, type.MakeArrayType());
				il.Emit(OpCodes.Stloc, instance); // instance = (type[])arg_1;
				
				// for (int i = 0; i < instance.Length; i++) write instance[i];
				
				var loopStart = il.DefineLabel();
				var loopHead = il.DefineLabel();
				var loopVariable = il.DeclareLocal(typeof(int));
				il.Emit(OpCodes.Ldc_I4_0);
				il.Emit(OpCodes.Stloc, loopVariable); // loopVariable = 0
				il.Emit(OpCodes.Br, loopHead); // goto loopHead;
				
				il.MarkLabel(loopStart);
				
				if (type.IsEnum || type.IsPrimitive) {
					if (type.IsEnum) {
						type = type.GetEnumUnderlyingType();
					}
					Debug.Assert(type.IsPrimitive);
					il.Emit(OpCodes.Ldloc, writer); // writer
					il.Emit(OpCodes.Ldloc, instance); // writer, instance
					il.Emit(OpCodes.Ldloc, loopVariable); // writer, instance, loopVariable
					switch (Type.GetTypeCode(type)) {
						case TypeCode.Boolean:
						case TypeCode.SByte:
						case TypeCode.Byte:
							il.Emit(OpCodes.Ldelem_I1); // writer, instance[loopVariable]
							il.Emit(callVirt, writeByte); // writer.Write(instance[loopVariable]);
							break;
						case TypeCode.Char:
						case TypeCode.Int16:
						case TypeCode.UInt16:
							il.Emit(OpCodes.Ldelem_I2); // writer, instance[loopVariable]
							il.Emit(callVirt, writeShort); // writer.Write(instance[loopVariable]);
							break;
						case TypeCode.Int32:
						case TypeCode.UInt32:
							il.Emit(OpCodes.Ldelem_I4);  // writer, instance[loopVariable]
							il.Emit(callVirt, writeInt); // writer.Write(instance[loopVariable]);
							break;
						case TypeCode.Int64:
						case TypeCode.UInt64:
							il.Emit(OpCodes.Ldelem_I8);  // writer, instance[loopVariable]
							il.Emit(callVirt, writeLong); // writer.Write(instance[loopVariable]);
							break;
						case TypeCode.Single:
							il.Emit(OpCodes.Ldelem_R4);  // writer, instance[loopVariable]
							il.Emit(callVirt, writeFloat); // writer.Write(instance[loopVariable]);
							break;
						case TypeCode.Double:
							il.Emit(OpCodes.Ldelem_R8);  // writer, instance[loopVariable]
							il.Emit(callVirt, writeDouble); // writer.Write(instance[loopVariable]);
							break;
						default:
							throw new NotSupportedException("Unknown primitive type " + type);
					}
				} else {
					il.Emit(OpCodes.Ldloc, instance); // instance
					il.Emit(OpCodes.Ldloc, loopVariable); // instance, loopVariable
					il.Emit(OpCodes.Ldelem, type); // instance[loopVariable]
					EmitWriteValueType(il, writer, type);
				}
				
				il.Emit(OpCodes.Ldloc, loopVariable); // loopVariable
				il.Emit(OpCodes.Ldc_I4_1); // loopVariable, 1
				il.Emit(OpCodes.Add); // loopVariable+1
				il.Emit(OpCodes.Stloc, loopVariable); // loopVariable++;
				
				il.MarkLabel(loopHead);
				il.Emit(OpCodes.Ldloc, loopVariable); // loopVariable
				il.Emit(OpCodes.Ldloc, instance); // loopVariable, instance
				il.Emit(OpCodes.Ldlen); // loopVariable, instance.Length
				il.Emit(OpCodes.Conv_I4);
				il.Emit(OpCodes.Blt, loopStart); // if (loopVariable < instance.Length) goto loopStart;
			} else if (type.IsValueType) {
				// boxed value type
				if (type.IsEnum || type.IsPrimitive) {
					il.Emit(OpCodes.Ldloc, writer);
					il.Emit(OpCodes.Ldarg_1);
					il.Emit(OpCodes.Unbox_Any, type);
					WritePrimitiveValue(il, type);
				} else {
					il.Emit(OpCodes.Ldarg_1);
					il.Emit(OpCodes.Unbox_Any, type);
					EmitWriteValueType(il, writer, type);
				}
			} else {
				// reference type
				var instance = il.DeclareLocal(type);
				il.Emit(OpCodes.Ldarg_1);
				il.Emit(OpCodes.Castclass, type);
				il.Emit(OpCodes.Stloc, instance); // instance = (type)arg_1;
				
				foreach (FieldInfo field in fields) {
					EmitWriteField(il, writer, instance, field); // write instance.Field
				}
			}
			il.Emit(OpCodes.Ret);
			return (ObjectWriter)dynamicMethod.CreateDelegate(typeof(ObjectWriter));
		}
Пример #27
0
		/// <summary>
		/// Writes a primitive value of the specified type.
		/// Stack transition: ..., writer, value => ...
		/// </summary>
		void WritePrimitiveValue(ILGenerator il, Type fieldType)
		{
			if (fieldType.IsEnum) {
				fieldType = fieldType.GetEnumUnderlyingType();
				Debug.Assert(fieldType.IsPrimitive);
			}
			switch (Type.GetTypeCode(fieldType)) {
				case TypeCode.Boolean:
				case TypeCode.SByte:
				case TypeCode.Byte:
					il.Emit(callVirt, writeByte); // writer.Write(value);
					break;
				case TypeCode.Char:
				case TypeCode.Int16:
				case TypeCode.UInt16:
					il.Emit(callVirt, writeShort); // writer.Write(value);
					break;
				case TypeCode.Int32:
				case TypeCode.UInt32:
					il.Emit(callVirt, writeInt); // writer.Write(value);
					break;
				case TypeCode.Int64:
				case TypeCode.UInt64:
					il.Emit(callVirt, writeLong); // writer.Write(value);
					break;
				case TypeCode.Single:
					il.Emit(callVirt, writeFloat); // writer.Write(value);
					break;
				case TypeCode.Double:
					il.Emit(callVirt, writeDouble); // writer.Write(value);
					break;
				default:
					throw new NotSupportedException("Unknown primitive type " + fieldType);
			}
		}
Пример #28
0
        private string CType(Type t, UnmanagedType? customType = null) {
            switch (t.Name) {
                case "Byte":
                case "byte":
                    return "unsigned __int8";
                case "SByte":
                case "sbyte":
                    return "__int8";
                case "int":
                case "Int32":
                    return "__int32";
                case "uint":
                case "UInt32":
                    return "unsigned __int32";
                case "Int16":
                case "short":
                    return "__int16";
                case "UInt16":
                case "ushort":
                    return "unsigned __int16";
                case "Int64":
                case "long":
                    return "__int64";
                case "UInt64":
                case "ulong":
                    return "unsigned __int64";
                case "Single":
                case "float":
                    return "float";
                case "Double":
                case "double":
                    return "double";
                case "Char":
                case "char":
                    return "wchar_t";
                case "bool":
                case "Boolean":
                    return "bool";
                case "string":
                case "String":
                    if (customType.HasValue && customType.Value == UnmanagedType.LPWStr) {
                        return "const wchar_t*";
                    }
                    return "const char_t*";


                case "IntPtr":
                    return "void*";
            }

            if (t.IsEnum) {
                if (enumTypeDefs.ContainsKey(t.Name)) {
                    return t.Name;
                }
                var enumType = CType(t.GetEnumUnderlyingType());


                var enumValues = t.GetEnumValues();

                var first = true;
                var evitems = string.Empty;
                foreach (var ev in enumValues) {
                    evitems += "{2}\r\n    {0} = {1}".format(t.GetEnumName(ev), (int) ev, first ? "" : ",");
                    first = false;
                }

                var tyepdefenum = "typedef enum  {{ {2}\r\n}} {0};\r\n".format(t.Name, enumType, evitems); /* : {1} */
                enumTypeDefs.Add(t.Name, tyepdefenum);
                return t.Name;
            }

            return "/* UNKNOWN : {0} */".format(t.Name);
        }
Пример #29
0
            Type LoadType(System.Type refType, bool loadAttributes)
            {
                Type           type;
                TypeAttributes typeAttributes = refType.Attributes;

                if (refType.IsClass)
                {
                    if (refType.BaseType?.Name == "Activity")
                    {
                        // For some reason, Android types that extend Activity fail to load for reflection on OS X.
                        // They don't need to be reflected anyway since they are always skipped by the adapter.
                        return(null);
                    }

                    if (typeof(MulticastDelegate).IsAssignableFrom(refType.BaseType))
                    {
                        Method invokeMethod = (Method)LoadMember(refType.GetMethod("Invoke"), loadAttributes);

                        Delegate delegateType = new Delegate
                        {
                            ReturnType = invokeMethod.ReturnType,
                            Parameters = invokeMethod.Parameters,
                        };
                        type = delegateType;
                    }
                    else
                    {
                        // A class is detected as static if it is sealed and abstract, or if there are
                        // no instance member properties, methods, or events.
                        bool isStatic = true;
                        if (!(refType.IsSealed && refType.IsAbstract))
                        {
                            foreach (MemberInfo member in
                                     refType.GetMembers(BindingFlags.Public | BindingFlags.Instance))
                            {
                                if (member.DeclaringType.Name != "Object" &&
                                    member.DeclaringType.Name != "NSObject" &&
                                    member.Name != "ClassHandle" &&
                                    member.Name != "get_ClassHandle")
                                {
                                    isStatic = false;
                                    break;
                                }
                            }
                        }

                        if (isStatic)
                        {
                            typeAttributes |= TypeAttributes.Sealed | TypeAttributes.Abstract;
                        }

                        Class classType = new Class
                        {
                            IsStatic      = isStatic,
                            IsSealed      = isStatic || refType.IsSealed,
                            IsAbstract    = isStatic || refType.IsAbstract,
                            ExtendsType   = GetTypeFullName(refType.BaseType),
                            IsGenericType = refType.IsGenericTypeDefinition,
                        };
                        classType.ImplementsTypes      = refType.GetInterfaces().Select(i => GetTypeFullName(i)).ToList();
                        classType.GenericArgumentNames = (refType.IsGenericTypeDefinition ?
                                                          refType.GetGenericArguments().Select(t => t.Name).ToList() : null);
                        type = classType;
                    }
                }
                else if (refType.IsInterface)
                {
                    Interface interfaceType = new Interface();
                    interfaceType.ExtendsTypes         = refType.GetInterfaces().Select(i => GetTypeFullName(i)).ToList();
                    interfaceType.GenericArgumentNames = (refType.IsGenericTypeDefinition ?
                                                          refType.GetGenericArguments().Select(t => t.Name).ToList() : null);
                    type = interfaceType;
                }
                else if (refType.IsEnum)
                {
                    Enum enumType = new Enum
                    {
                        UnderlyingType = GetTypeFullName(refType.GetEnumUnderlyingType()),
                    };
                    type = enumType;
                }
                else if (refType.IsValueType)
                {
                    Struct structType = new Struct();
                    structType.ImplementsTypes      = refType.GetInterfaces().Select(i => GetTypeFullName(i)).ToList();
                    structType.GenericArgumentNames = (refType.IsGenericTypeDefinition ?
                                                       refType.GetGenericArguments().Select(t => t.Name).ToList() : null);
                    type = structType;
                }
                else
                {
                    throw new NotSupportedException("Unsupported type: " + GetTypeFullName(refType));
                }

                type.Name       = GetTypeName(refType);
                type.Namespace  = refType.Namespace;
                type.Attributes = typeAttributes;

                if (loadAttributes)
                {
                    type.CustomAttributes = LoadAttributes(refType.CustomAttributes);
                }

                if (!(type is Delegate))
                {
                    LoadMembers(refType, type, loadAttributes);
                }

                return(type);
            }
Пример #30
0
        private static void WriteEnumListHex(string fileName, string enumName, Type enumType, bool writeValues = true)
        {
            bool isFlagsEnum = false;
            object[] memInfo = enumType.GetCustomAttributes(typeof(FlagsAttribute), false);
            isFlagsEnum = memInfo.Length > 0;

            TextWriter tw = new StreamWriter(fileName);

            WriteHeader1(tw, enumName);
            WriteCode(tw, enumType.FullName);
            if (writeValues)
            {
                tw.Write(" : ");
                WriteCode(tw, enumType.GetEnumUnderlyingType().Name);
            }

            if (isFlagsEnum)
            {
                tw.WriteLine();
                tw.WriteLine();
                WriteCode(tw, "[Flags]");
            }

            tw.WriteLine();
            WriteHorizonalLine(tw);
            tw.WriteLine();
            Array temp2 = Enum.GetValues(enumType);

            List<String> tempList = new List<string>();

            int max = temp2.Length;
            foreach (object v in temp2)
            {
                string eName = Enum.GetName(enumType, v);
                string tempString = "**" + eName + "**";

                if (writeValues)
                {
                    object underlyingValue = Convert.ChangeType(v, Enum.GetUnderlyingType(v.GetType()));
                    tempString+=" = 0x" + ((int)underlyingValue).ToString("X8");
                }

                max--;
                if (max > 0)
                {
                    tempString+=",";
                }

                tempList.Add(tempString);
            }

            tempList.Sort();
            foreach (string s in tempList)
            {
                tw.WriteLine(s);
                tw.WriteLine();
            }

            WriteFooter(tw);
            tw.Close();
        }
Пример #31
0
 static bool IsSignedEnum(Type enumType)
 {
     return SignedFieldHandler.IsCompatibleWith(enumType.GetEnumUnderlyingType());
 }
        /// <summary>
        /// Creates a new <see cref="CodeTypeDeclaration"/> that is the generated form of
        /// the given <paramref name="enumType"/>.
        /// </summary>
        /// <param name="enumType">The enum type to generate.</param>
        /// <param name="codeGenerator">The current proxy generator context.</param>
        /// <returns>The newly generated enum type declaration.</returns>
        internal static CodeTypeDeclaration CreateEnumTypeDeclaration(Type enumType, CodeDomClientCodeGenerator codeGenerator)
        {
            System.Diagnostics.Debug.Assert(enumType.IsEnum, "Type must be an enum type");

            CodeTypeDeclaration typeDecl = CodeGenUtilities.CreateTypeDeclaration(enumType);
            typeDecl.IsEnum = true;

            // Always force generated enums to be public
            typeDecl.TypeAttributes |= TypeAttributes.Public;

            // Enums deriving from anything but int get an explicit base type
            Type underlyingType = enumType.GetEnumUnderlyingType();
            if (underlyingType != typeof(int))
            {
                typeDecl.BaseTypes.Add(new CodeTypeReference(underlyingType));
            }

            // Generate [DataContract] if it appears in the original only.  Use Reflection only because that matches
            // what WCF will do.
            DataContractAttribute dataContractAttr = (DataContractAttribute)Attribute.GetCustomAttribute(enumType, typeof(DataContractAttribute));
            if (dataContractAttr != null)
            {
                CodeAttributeDeclaration attrDecl = CodeGenUtilities.CreateDataContractAttributeDeclaration(enumType, codeGenerator, typeDecl);
                typeDecl.CustomAttributes.Add(attrDecl);
            }

            string[] memberNames = Enum.GetNames(enumType);
            Type enumValueType = Enum.GetUnderlyingType(enumType);
            for (int i = 0; i < memberNames.Length; ++i)
            {
                string memberName = memberNames[i];
                CodeTypeReference enumTypeRef = CodeGenUtilities.GetTypeReference(enumValueType, codeGenerator, typeDecl);
                CodeMemberField enumMember = new CodeMemberField(enumTypeRef, memberName);

                // Generate an initializer for the enum member.
                // GetRawConstantValue is the safest way to get the raw value of the enum field
                // and works for both Reflection and ReflectionOnly loaded assemblies.
                FieldInfo fieldInfo = enumType.GetField(memberName);
                if (fieldInfo != null)
                {
                    object memberValue = fieldInfo.GetRawConstantValue();

                    Debug.Assert(memberValue != null, "Enum type's GetRawConstantValue should never return null");

                    // We special-case MinValue and MaxValue for the integral types
                    // because VisualBasic will generate overflow compiler error for
                    // Int64.MinValue.   If we detect a known MinValue or MaxValue for
                    // this integral type, we generate that reference, otherwise we
                    // just generate a constant integral value of the enum's type
                    object[] minMaxValues = null;
                    CodeGenUtilities.integralMinMaxValues.TryGetValue(underlyingType, out minMaxValues);
                    Debug.Assert(minMaxValues == null || minMaxValues.Length == 3, "integralMinMaxValues elements must always contain 3 values");

                    // Gen xxx.MinValue if it matches, but give precedence to matching a true zero,
                    // which is the min value for the unsigned integral types
                    // minMaxValues[0]: the MinValue for this type
                    // minMaxValues[1]: the MaxValue for this type
                    // minMaxValues[2]: the zero for this type (memberValue is not boxed and cannot be cast)
                    if (minMaxValues != null && !memberValue.Equals(minMaxValues[2]) && memberValue.Equals(minMaxValues[0]))
                    {
                         enumMember.InitExpression = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(underlyingType), "MinValue");
                    }
                    // Gen xxx.MaxValue if it matches
                    else if (minMaxValues != null && memberValue.Equals(minMaxValues[1]))
                    {
                         enumMember.InitExpression = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(underlyingType), "MaxValue");
                    }
                    // All other cases generate an integral constant.
                    // CodeDom knows how to generate the right integral constant based on memberValue's type.
                    else
                    {
                         enumMember.InitExpression = new CodePrimitiveExpression(memberValue);
                    }
                }

                typeDecl.Members.Add(enumMember);

                // Generate an [EnumMember] if appropriate
                EnumMemberAttribute enumMemberAttr = (EnumMemberAttribute)Attribute.GetCustomAttribute(fieldInfo, typeof(EnumMemberAttribute));
                if (enumMemberAttr != null)
                {
                    CodeAttributeDeclaration enumAttrDecl = CodeGenUtilities.CreateEnumMemberAttributeDeclaration(fieldInfo, codeGenerator, typeDecl);
                    enumMember.CustomAttributes.Add(enumAttrDecl);
                }

                // Propagate any other attributes that can be seen by the client
                CustomAttributeGenerator.GenerateCustomAttributes(
                    codeGenerator,
                    typeDecl,
                    ex => string.Format(CultureInfo.CurrentCulture, Resource.ClientCodeGen_Attribute_ThrewException_CodeTypeMember, ex.Message, fieldInfo.Name, typeDecl.Name, ex.InnerException.Message),
                    fieldInfo.GetCustomAttributes(false).Cast<Attribute>().Where(a => a.GetType() != typeof(EnumMemberAttribute)),
                    enumMember.CustomAttributes,
                    enumMember.Comments);
            }

            // Attributes marked with [Flag] propagate it
            if (enumType.GetCustomAttributes(typeof(FlagsAttribute), false).Length > 0)
            {
                CodeAttributeDeclaration attrDecl = CodeGenUtilities.CreateAttributeDeclaration(typeof(FlagsAttribute), codeGenerator, typeDecl);
                typeDecl.CustomAttributes.Add(attrDecl);
            }
            return typeDecl;
        }
Пример #33
0
 private static bool IsTypeConversionRequired(Type source, Type target)
 {
     if (target.IsEnum) return !target.GetEnumUnderlyingType().IsAssignableFrom(source);
     return !target.IsAssignableFrom(source);
 }
Пример #34
0
 /// <summary>
 /// Gets the memory used for the given type
 /// </summary>
 /// <param name="type">The type</param>
 /// <param name="plusInnerStructure">Determines whether the inner structure of the type has to be considered</param>
 /// <returns>The memory consumed by an instance of the given type (in bytes)</returns>
 private static long GetTypeSize(Type type, out bool plusInnerStructure)
 {
     plusInnerStructure = false;
     if (type.IsEnum)
     {
         return GetTypeSize(type.GetEnumUnderlyingType(), out plusInnerStructure);
     }
     else if (type == typeof(double))
     {
         return sizeof(double);
     }
     else if (type == typeof(float))
     {
         return sizeof(float);
     }
     else if (type == typeof(char))
     {
         return sizeof(char);
     }
     else if (type == typeof(short))
     {
         return sizeof(short);
     }
     else if (type == typeof(int))
     {
         return sizeof(int);
     }
     else if (type == typeof(long))
     {
         return sizeof(long);
     }
     else if (type == typeof(ushort))
     {
         return sizeof(ushort);
     }
     else if (type == typeof(uint))
     {
         return sizeof(uint);
     }
     else if (type == typeof(ulong))
     {
         return sizeof(ulong);
     }
     else if (type == typeof(decimal))
     {
         return sizeof(decimal);
     }
     else if (type == typeof(byte))
     {
         return sizeof(byte);
     }
     else if (type == typeof(sbyte))
     {
         return sizeof(sbyte);
     }
     else if (type == typeof(bool))
     {
         return sizeof(bool);
     }
     else
     {
         plusInnerStructure = true;
         return type.IsValueType ? 0 : MemoryForObject;
     }
 }
Пример #35
0
        private static object Parse(Type type, string input, NumberStyles style = NumberStyles.Integer)
        {
            if(type.IsEnum)
            {
                return Parse(type.GetEnumUnderlyingType(), input, style);
            }
            if(type == typeof(int))
            {   
                return int.Parse(input, style);
            }
            if(type == typeof(uint))
            {
                return uint.Parse(input, style);
            }

            throw new ArgumentException(string.Format("Unsupported type for parsing: {0}", type.Name));
        }
Пример #36
0
        private static DataType BuildDataType(Type type, Func<Type, MemberInfo, int> membersOrder, HashSet<Type> cycleCheck)
        {
            if (DataType.IsPrimitiveType(type))
                return DataType.FromPrimitiveType(type);

            if (type.IsEnum)
                return DataType.FromPrimitiveType(type.GetEnumUnderlyingType());

            if (type == typeof(Guid))
                return DataType.ByteArray;

            if (type.IsKeyValuePair())
            {
                return DataType.Slots(
                    BuildDataType(type.GetGenericArguments()[0], membersOrder, cycleCheck),
                    BuildDataType(type.GetGenericArguments()[1], membersOrder, cycleCheck));
            }

            if (type.IsArray)
                return DataType.Array(BuildDataType(type.GetElementType(), membersOrder, cycleCheck));

            if (type.IsList())
                return DataType.List(BuildDataType(type.GetGenericArguments()[0], membersOrder, cycleCheck));

            if (type.IsDictionary())
            {
                return DataType.Dictionary(
                    BuildDataType(type.GetGenericArguments()[0], membersOrder, cycleCheck),
                    BuildDataType(type.GetGenericArguments()[1], membersOrder, cycleCheck));
            }

            if (type.IsNullable())
                return DataType.Slots(BuildDataType(type.GetGenericArguments()[0], membersOrder, cycleCheck));

            List<DataType> slots = new List<DataType>();
            foreach (var member in GetPublicMembers(type, membersOrder))
            {
                var memberType = member.GetPropertyOrFieldType();

                if (cycleCheck.Contains(memberType))
                    throw new NotSupportedException(String.Format("Type {0} has cycle declaration.", memberType));

                cycleCheck.Add(memberType);
                DataType slot = BuildDataType(memberType, membersOrder, cycleCheck);
                cycleCheck.Remove(memberType);
                slots.Add(slot);
            }

            if (slots.Count == 0)
                throw new NotSupportedException(String.Format("{0} do not contains public read/writer properties and fields", type));

            return DataType.Slots(slots.ToArray());
        }