为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
守着一只汪 2023-09-24 10:40:22
假设我们有以下两个类的定义: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(...)实施呢?
查看完整描述

1 回答

?
互换的青春

TA贡献1797条经验 获得超6个赞

考虑到可能有多个属性,GetChildTypeOf返回List<Type>对象越好。


private static List<Type> GetChildTypeOf(Type parent)

{

    var res = new List<Type>();


    var props = parent.GetProperties();

    foreach (var prop in props)

    {

        var propType = prop.PropertyType;

        var elementType = propType.GetElementType();

        res.Add(elementType);

    }


    return res;

}

然后你做出你的断言:


var childType = GetChildTypeOf(typeof(ParentClass));

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

也许如果有一种方法可以返回所有这些元素,并且有一种方法可以通过给定的属性名称返回子类型元素,那就更好了。


编辑:以下是查找特定属性名称的方式:


private static Type GetSpecificChildTypeOf(Type parent, string propertyName)

{

    var propType = typeof(ParentClass).GetProperty(propertyName).PropertyType;

    var elementType = propType.GetElementType();


    return elementType;

}

并像这样使用它:


var childType = GetSpecificChildTypeOf(typeof(ParentClass), "Children");

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

编辑:感谢您标记答案!


查看完整回答
反对 回复 2023-09-24
  • 1 回答
  • 0 关注
  • 53 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信