Fork me on GitHub

C# 通过反射获取类字段名和值并加入到字典中(包含递归获取)

方式1(推荐)

using System;
using System.Collections.Generic;
 
public class EntityData
{
    public string Name { get; set; }
    public int Age { get; set; }
}
 
class Program
{
    static void Main(string[] args)
    {
        // 创建一个新的实体数据对象
        var entity = new EntityData()
        {
            Name = "John",
            Age = 25
        };
        
        // 创建一个空的字典
        var dictionary = new Dictionary<string, object>();
        
        // 获取实体数据的所有属性信息
        var properties = typeof(EntityData).GetProperties();
        
        foreach (var property in properties)
        {
            // 添加键值对到字典中
            dictionary[property.Name] = property.GetValue(entity);
        }
        
        // 输出结果
        Console.WriteLine("Dictionary Contents:");
        foreach (var kvp in dictionary)
        {
            Console.WriteLine($"{kvp.Key}: {kvp.Value}");
        }
    }
}

 

方式2(包含递归)

//测试类

public class HKAddvisitor1
{
    public string code { set; get; }
    public string msg { set; get; }
    public string data { set; get; }
}

 

//调用

HKAddvisitor1 hKAddvisitor1 = new HKAddvisitor1()
{
    code = "1",
    data = "2",
    msg = "搞定",
};

GetFields(hKAddvisitor1);

 

 

//基础方法

Dictionary<string, string> GetFields<T>(T t)
{
    Dictionary<string, string> fields = new Dictionary<string, string>();
    var type = t.GetType().GetProperties();
    foreach (PropertyInfo item in type)
    {
        var typeName = item.PropertyType.Name;
        if (typeName == "Nullable`1")
        {
            typeName = item.PropertyType.GenericTypeArguments.FirstOrDefault().Name;
        }
        Console.WriteLine("{0}-->{1}", item.Name, item.GetValue(t));
    }
    return fields;
}

 

//递归测试类
public class HKAddvisitor1
{
    public string sucode { set; get; }
    public string sumsg { set; get; }
    public string sudata { set; get; }
}

public class HKAddvisitor
{
    public string code { set; get; }
    public string msg { set; get; }
    public HKAddvisitor1 data { set; get; }
}

 

//递归调用
HKAddvisitor hKAddvisitor = new HKAddvisitor()
{
    code = "1",
    msg = "搞定",
    data = new HKAddvisitor1
    {
        sucode = "2",
        sumsg = "heheh",
        sudata = "dsa"
    }
};

 

Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
 GetInfoPropertys(hKAddvisitor, keyValuePairs);
foreach (var item in keyValuePairs)
{
    Console.WriteLine("属性名:{0},属性值:{1}", item.Key, item.Value);
}

 

//递归获取

void GetInfoPropertys(object objInfo, Dictionary<string, string> keyValuePairs)
{
    StringBuilder strB = new System.Text.StringBuilder();
    if (objInfo == null) return;
    Type tInfo = objInfo.GetType();
    PropertyInfo[] pInfos = tInfo.GetProperties();
    if (tInfo.IsGenericType)
    {
        System.Collections.ICollection Ilist = objInfo as System.Collections.ICollection;
        if (Ilist != null)
        {
            strB.AppendFormat("集合⼦属性{0}<br/>", Ilist.Count);
            foreach (object obj in Ilist)
            {
                GetInfoPropertys(obj, keyValuePairs);
            }
        }
        else
        {
            strB.Append("泛型集合为空<br/>");
        }
        return;
    }
    foreach (PropertyInfo pTemp in pInfos)
    {
        string Pname = pTemp.Name;
        string pTypeName = pTemp.PropertyType.Name;
        object Pvalue = pTemp.GetValue(objInfo, null);
        if (pTemp.PropertyType.IsValueType || pTemp.PropertyType.Name.StartsWith("String"))
        {
            string value = (Pvalue == null ? "" : Pvalue.ToString());
            keyValuePairs.Add(Pname, value);
            Console.WriteLine("属性名:{0},属性类型:{1},属性值:{2}<br/>", Pname, pTypeName, value);
            strB.AppendFormat("属性名:{0},属性类型:{1},属性值:{2}<br/>", Pname, pTypeName, value);
        }
        else
        {
            //string value = Pvalue == null ? "" : Pvalue.ToString();
            //Console.WriteLine("<br/><b>⼦类</b>,属性名:{0},属性类型:{1},属性值:{2}<br/>", Pname, pTypeName, value);
            //strB.AppendFormat("<br/><b>⼦类</b>,属性名:{0},属性类型:{1},属性值:{2}<br/>", Pname, pTypeName, value);
            //keyValuePairs.Add(Pname, value);
            //strB.Append("----------------------------------------------<br/>");
            GetInfoPropertys(Pvalue, keyValuePairs);
        }
    }
}

 

//拓展

 https://www.cnblogs.com/bmyblogs/p/9346843.html   (判断属性类型)

https://wenku.baidu.com/view/6b904c485bfafab069dc5022aaea998fcc2240e4.html   (递归)

posted @ 2022-06-16 10:42  WantRemake  阅读(1106)  评论(0编辑  收藏  举报