C#实现获取非静态类实例属性名称、值及数据类型的方法需求
C#实现获取非静态类实例属性名称、值及数据类型的方法需求
嗨,我来帮你搞定这个需求!要实现这个获取类实例属性信息的方法,我们可以利用C#的反射机制来动态读取对象的属性细节,完全符合你要的返回格式。
首先先明确你的核心需求:
- 输入任意类的实例(
object类型) - 返回一个
List<(string[], string[], string[])>,其中元组的三个数组分别对应:- 所有属性的名称数组
- 对应属性的取值数组(
null也要保留) - 对应属性的完整数据类型名称数组(比如
System.String、System.Int32)
接下来直接上实现代码,我会逐行解释关键细节:
using System; using System.Collections.Generic; using System.Reflection; public class PropertyInfoHelper { public List<(string[], string[], string[])> GetClassPropertyInfo(object instance) { // 先判断输入实例是否为空,避免空引用异常 if (instance == null) throw new ArgumentNullException(nameof(instance), "输入的类实例不能为null"); // 获取实例的运行时类型信息 Type type = instance.GetType(); // 获取所有公共实例属性(排除静态属性) PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); // 初始化三个数组,长度和属性数量一致 string[] propertyNames = new string[properties.Length]; string[] propertyValues = new string[properties.Length]; string[] propertyTypes = new string[properties.Length]; // 遍历每个属性,填充三个数组 for (int i = 0; i < properties.Length; i++) { PropertyInfo prop = properties[i]; // 填充属性名称 propertyNames[i] = prop.Name; // 获取属性值,特殊处理null的情况 object value = prop.GetValue(instance); propertyValues[i] = value?.ToString() ?? "null"; // 获取属性的完整类型名称(包含命名空间) propertyTypes[i] = prop.PropertyType.FullName; } // 将三个数组打包成元组,放入List中返回(符合你的方法定义) return new List<(string[], string[], string[])> { (propertyNames, propertyValues, propertyTypes) }; } }
关键细节说明:
- 用
GetType()获取实例的运行时类型,再通过GetProperties指定BindingFlags筛选出公共实例属性,排除静态属性 - 处理属性值时,用
value?.ToString() ?? "null"避免null值调用ToString()时出现空引用异常 prop.PropertyType.FullName会返回带命名空间的完整类型名称,完全匹配你需要的System.Int32、System.String这类格式
使用示例(用你给出的Animal类测试):
// 你的Animal类定义 public class Animal { public string AnimalName { get; set; } public string AnimalType { get; set; } public int AnimalAgeInMonths { get; set; } } // 调用示例 class Program { static void Main() { Animal animal = new Animal(); animal.AnimalName = null; animal.AnimalType = "Sheep"; animal.AnimalAgeInMonths = 7; PropertyInfoHelper helper = new PropertyInfoHelper(); var result = helper.GetClassPropertyInfo(animal); // 输出结果验证 var infoTuple = result[0]; Console.WriteLine("属性名称:"); foreach (var name in infoTuple.Item1) Console.WriteLine($"- {name}"); Console.WriteLine("\n属性值:"); foreach (var value in infoTuple.Item2) Console.WriteLine($"- {value}"); Console.WriteLine("\n数据类型:"); foreach (var type in infoTuple.Item3) Console.WriteLine($"- {type}"); } }
运行后输出结果:
属性名称: - AnimalName - AnimalType - AnimalAgeInMonths 属性值: - null - Sheep - 7 数据类型: - System.String - System.String - System.Int32
完全匹配你想要的效果!如果之后需要处理非公共属性、索引器等特殊场景,只需要调整GetProperties的BindingFlags参数即可。
备注:内容来源于stack exchange,提问作者winscripter
相关产品推荐
相关产品推荐

