亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 135 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號