hutongqing
2025-01-04 0ba846024a89bbdfe2b2e2183d0ed944ac9782bf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using WIDESEAWCS_Common.Attributes;
 
namespace WIDESEAWCS_Common.Helper
{
    public static class ConvertHelper
    {
        public static bool[] ByteToBoolArray(this byte data)
        {
            bool[] result = new bool[8];
            for (int i = 0; i < 8; i++)
            {
                result[i] = (data & (1 << i)) != 0;
            }
            return result;
        }
 
        public static T ByteToBoolObject<T>(this byte data)
        {
            bool[] boolArray = ByteToBoolArray(data);
 
            //Array.Reverse(boolArray);
 
            Type type = typeof(T);
            object? obj = Activator.CreateInstance(type);
            if (obj == null)
            {
                throw new Exception($"类型实例化错误");
            }
            T result = (T)obj;
 
            PropertyInfo[] propertyInfos = type.GetProperties();
            foreach (PropertyInfo propertyInfo in propertyInfos)
            {
                BoolIndexAttribute? boolIndexAttribute = propertyInfo.GetCustomAttribute<BoolIndexAttribute>();
                if (boolIndexAttribute != null)
                {
                    if (boolIndexAttribute.Index >= 0 && boolIndexAttribute.Index < 8)
                    {
                        propertyInfo.SetValue(result, boolArray[boolIndexAttribute.Index]);
                    }
                }
            }
 
            return result;
        }
    }
}