how to get all primitive type of an object

前端 未结 4 1645
夕颜
夕颜 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条回答
  •  梦毁少年i
    2020-12-20 02:08

    You need to keep track of types you've already checked.

    public static List ProcessType(Type type)
    {
        return ProcessType(type, new List());
    }
    public static List ProcessType(Type type, List processedTypes)
    {
        // Keep track of results
        var result = new List();
    
        // Iterate properties of the type
        foreach (var property in type.GetProperties())
        {
            var propertyType = property.PropertyType;
    
            // If the property has a primitive type
            if (propertyType.IsPrimitive)
            {
                // add it to the results
                result.Add(property);
            }
            // If the property has a non-primitive type
            // and it has not been processed yet
            else if (!processedTypes.Contains(propertyType))
            {
                // Mark the property's type as already processed
                processedTypes.Add(propertyType);
    
                // Recursively processproperties of the property's type
                result.AddRange(ProcessType(propertyType, processedTypes));
            }
        }
    
        return result;
    }
    

提交回复
热议问题