打印实例类中所有属性名和值

    private void PrintPropertyInfo(object classInstance)
    {
        PropertyInfo[] props = classInstance.GetType().GetProperties();
        foreach (PropertyInfo info in props)
        {
            object value = info.GetValue(classInstance, null);
            // 使用info.GetType()不会得到准确类型
            Debug.LogFormat("属性名: {0}, 属性值:{1}", info.Name, value);
            if (IsListT(info.PropertyType))
            {
                // 获取List<T>的T的类型
                Type listType = value.GetType().GetGenericArguments()[0];
                Debug.LogFormat("列表类型: {0}", listType);
                IEnumerable list = (IEnumerable)value;
                foreach (var item in list)
                {
                    Debug.LogFormat("列表 单位值: {0}", item);
                }
            }
        }

    }

    private bool IsListT(Type type)
    {
        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
        {
            return true;
        }
        return false;

    }

猜你喜欢

转载自blog.csdn.net/zhuangjialo/article/details/122808440
今日推荐