示例#1
0
文件: Struct.cs 项目: LInJunYue/netch
        private static byte[] ConvertEndian <T>(byte[] data)
        {
            Type type = typeof(T);

            FieldInfo[]     fields = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            EndianAttribute endian = null;

            if (type.GetTypeInfo().IsDefined(typeof(EndianAttribute), false))
            {
                endian = (EndianAttribute)type.GetTypeInfo().GetCustomAttributes(typeof(EndianAttribute), false).First();
            }

            foreach (FieldInfo field in fields)
            {
                if (endian == null && !field.IsDefined(typeof(EndianAttribute), false))
                {
                    continue;
                }

                int offset = Marshal.OffsetOf <T>(field.Name).ToInt32();
#pragma warning disable 618
                int length = Marshal.SizeOf(field.FieldType);
#pragma warning restore 618
                endian = endian ?? (EndianAttribute)field.GetCustomAttributes(typeof(EndianAttribute), false).First();

                if (endian.Endianness == Endianness.Big && BitConverter.IsLittleEndian ||
                    endian.Endianness == Endianness.Little && !BitConverter.IsLittleEndian)
                {
                    Array.Reverse(data, offset, length);
                }
            }

            return(data);
        }
示例#2
0
        private static byte[] ConvertEndian(Type type, byte[] data)
        {
            var             fields = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            EndianAttribute endian = null;

            if (type.IsDefined(typeof(EndianAttribute), false))
            {
                endian = (EndianAttribute)type.GetCustomAttributes(typeof(EndianAttribute), false)[0];
            }

            foreach (FieldInfo field in fields)
            {
                if (endian == null && !field.IsDefined(typeof(EndianAttribute), false))
                {
                    continue;
                }

                int offset = Marshal.OffsetOf(type, field.Name).ToInt32();
                int length = Marshal.SizeOf(field.FieldType);
                endian = endian ?? (EndianAttribute)field.GetCustomAttributes(typeof(EndianAttribute), false)[0];

                if (endian.Endianness == Endianness.Big && BitConverter.IsLittleEndian ||
                    endian.Endianness == Endianness.Little && !BitConverter.IsLittleEndian)
                {
                    Array.Reverse(data, offset, length);
                }
            }

            return(data);
        }