c# – 获取嵌套属性及其父级的全名
发布时间:2020-12-15 23:50:34 所属栏目:百科 来源:网络整理
导读:如何通过C#中的反射获取其父级的嵌套属性的全名?我的意思是,例如我们有这个类: public class Student{ public int StudentID { get; set; } public string StudentName { get; set; } public DateTime? DateOfBirth { get; set; } public Grade Grade { ge
如何通过C#中的反射获取其父级的嵌套属性的全名?我的意思是,例如我们有这个类:
public class Student { public int StudentID { get; set; } public string StudentName { get; set; } public DateTime? DateOfBirth { get; set; } public Grade Grade { get; set; } } public class Grade { public int GradeId { get; set; } public string GradeName { get; set; } public string Section { get; set; } public GradGroup GradGroup { get; set; } } public class GradGroup { public int Id { get; set; } public string GroupName { get; set; } } 我有“GradGroup”和Student作为方法参数,并希望“Grade.GradeGroup”作为输出: public string GetFullPropertyName(Type baseType,string propertyName) { // how to implement that?? } 调用方法: GetFullPropertyName(typeof(Student),"GradeGroup"); // Output is Grade.GradeGroup 解决方法
该属性可能不是唯一的,因为它可能存在于多个组件上,因此您应该返回IEnumerable< string>.话虽这么说,您可以使用类型的GetProperties遍历属性树:
public static IEnumerable<string> GetFullPropertyName(Type baseType,string propertyName) { var prop = baseType.GetProperty(propertyName); if(prop != null) { return new[] { prop.Name }; } else if(baseType.IsClass && baseType != typeof(string)) // Do not go into primitives (condition could be refined,this excludes all structs and strings) { return baseType .GetProperties() .SelectMany(p => GetFullPropertyName(p.PropertyType,propertyName),(p,v) => p.Name + "." + v); } return Enumerable.Empty<string>(); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |