我是靠谱客的博主 狂野店员,这篇文章主要介绍C#获取实体类的属性名称和对应值一、定义实体类二、实例化类且赋值三、获取实体类的属性名称和对应值,现在分享给大家,希望可以做个参考。

一、定义实体类

复制代码
1
2
3
4
5
6
7
8
9
//人员信息模型类 private class PeopleInfo { public string ID { get; set; } public string Name { get; set; } public string Sex { get; set; } public string IdCard { get; set; } }

二、实例化类且赋值

复制代码
1
2
3
4
PeopleInfo peopleInfo= new PeopleInfo() { ID = "JK001", Name = "杨万里", Sex = "男", IdCard = "523033199001026780" };

三、获取实体类的属性名称和对应值

3.1、 获取到类中的所有属性名称和对应值方法

复制代码
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
/// <summary> /// 获取到类中的所有属性和对应值 /// </summary> /// <typeparam name="T">实体类型</typeparam> /// <param name="t">类实体</param> /// <returns>返回类中的所有属性和对应值</returns> public static string GetAllProperties<T>(T t) { string tStr = string.Empty; if (t == null) { return tStr; } System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); if (properties.Length <= 0) { return tStr; } foreach (System.Reflection.PropertyInfo item in properties) { string name = item.Name; object value = item.GetValue(t, null); if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String")) { tStr += string.Format("{0}:{1},", name, value); } else { GetAllProperties(value); } } return tStr; }

3.2、解析类中的所有属性和对应值字符串方法

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/// <summary> /// 解析类中的所有属性和对应值字符串 /// </summary> /// <param name="strClassAllProperties">类中的所有属性和对应值字符串</param> /// <returns>返回类中所有属性和对应值得键值对列表</returns> public static Dictionary<string,string> AnalyAllPropertiesString(string strClassAllProperties) { Dictionary<string, string> dic = new Dictionary<string, string>(); if (string.IsNullOrEmpty(strClassAllProperties)) return dic; string[] splitDatas = strClassAllProperties.Split(','); int len = splitDatas.Length - 1; for (int i = 0; i < len; i++) { string[] strSingle = splitDatas[i].Split(':'); dic.Add(strSingle[0],strSingle[1]); } return dic; }

3.3、获取实体类所有属性名称和对应值示例

复制代码
1
2
3
4
5
#获取到获取到PeopleInfo类中的所有属性和对应值 string str = Common.ClassOpc.GetAllProperties(peopleInfo); #输出结果如下: "ID:JK001,Name:杨万里,Sex:男,IdCard:523033199001026780,"

最后

以上就是狂野店员最近收集整理的关于C#获取实体类的属性名称和对应值一、定义实体类二、实例化类且赋值三、获取实体类的属性名称和对应值的全部内容,更多相关C#获取实体类内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(98)

评论列表共有 0 条评论

立即
投稿
返回
顶部