how to get all primitive type of an object

前端 未结 4 1643
夕颜
夕颜 2020-12-20 01:23

I wanna have all properties of an object which have primitive type, and if the object has a relation to another class , I wanna have the primitive properties of this another

4条回答
  •  离开以前
    2020-12-20 02:01

    You could keep a track of visited types to avoid recursion:

    public class A
    {
        public string Name { get; set; }
        public B B { get; set; }
    }
    
    public class B
    {
        public string Category { get; set; }
        public A A { get; set; }
    }
    
    class Program
    {
        static void Main()
        {
            var result = Visit(typeof(A));
            foreach (var item in result)
            {
                Console.WriteLine(item.Name);
            }
        }
    
        public static IEnumerable Visit(Type t)
        {
            var visitedTypes = new HashSet();
            var result = new List();
            InternalVisit(t, visitedTypes, result);
            return result;
        }
    
        private void InternalVisit(Type t, HashSet visitedTypes, IList result)
        {
            if (visitedTypes.Contains(t))
            {
                return;
            }
    
            if (!IsPrimitive(t))
            {
                visitedTypes.Add(t);
                foreach (var property in t.GetProperties())
                {
                    if (IsPrimitive(property.PropertyType))
                    {
                        result.Add(property);
                    }
                    InternalVisit(property.PropertyType, visitedTypes, result);
                }
            }
        }
    
        private static bool IsPrimitive(Type t)
        {
            // TODO: put any type here that you consider as primitive as I didn't
            // quite understand what your definition of primitive type is
            return new[] { 
                typeof(string), 
                typeof(char),
                typeof(byte),
                typeof(sbyte),
                typeof(ushort),
                typeof(short),
                typeof(uint),
                typeof(int),
                typeof(ulong),
                typeof(long),
                typeof(float),
                typeof(double),
                typeof(decimal),
                typeof(DateTime),
            }.Contains(t);
        }
    }
    

提交回复
热议问题