C#中如何获取另一个对象的属性的对象类型?

假设我们有以下两个类的定义:


public class ParentClass

{

   public ChildClass[] Children{ get; set; }

}


public class ChildClass

{

   public int Id{ get; set; }

}

ParentClass我们可以迭代using的属性System.Type,但我无法在 dotnet core 中找到一种方法来确定 的非数组Children类型ChildClass。例如,我希望始终能够通过以下测试:


Type childType = GetChildTypeOf(typeof(ParentClass));

Assert.True(childType == typeof(ChildClass));

那么,应该如何GetChildTypeOf(...)实施呢?


守着一只汪
浏览 57回答 1
1回答

互换的青春

考虑到可能有多个属性,GetChildTypeOf返回List<Type>对象越好。private static List<Type> GetChildTypeOf(Type parent){&nbsp; &nbsp; var res = new List<Type>();&nbsp; &nbsp; var props = parent.GetProperties();&nbsp; &nbsp; foreach (var prop in props)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var propType = prop.PropertyType;&nbsp; &nbsp; &nbsp; &nbsp; var elementType = propType.GetElementType();&nbsp; &nbsp; &nbsp; &nbsp; res.Add(elementType);&nbsp; &nbsp; }&nbsp; &nbsp; return res;}然后你做出你的断言:var childType = GetChildTypeOf(typeof(ParentClass));Assert.True(childType.First() == typeof(ChildClass));也许如果有一种方法可以返回所有这些元素,并且有一种方法可以通过给定的属性名称返回子类型元素,那就更好了。编辑:以下是查找特定属性名称的方式:private static Type GetSpecificChildTypeOf(Type parent, string propertyName){&nbsp; &nbsp; var propType = typeof(ParentClass).GetProperty(propertyName).PropertyType;&nbsp; &nbsp; var elementType = propType.GetElementType();&nbsp; &nbsp; return elementType;}并像这样使用它:var childType = GetSpecificChildTypeOf(typeof(ParentClass), "Children");Assert.True(childType == typeof(ChildClass))编辑:感谢您标记答案!
打开App,查看更多内容
随时随地看视频慕课网APP