簡體   English   中英

如何遍歷我的類屬性並獲取其類型?

[英]How do I loop through my class properties and get their types?

我想遍歷我的類的屬性並獲取每個屬性類型。 我大部分時間都得到了它,但是在嘗試獲取類型時,而不是獲取字符串,int等,我得到類型反射。 有任何想法嗎? 如果需要更多背景信息,請與我們聯系。 謝謝!

using System.Reflection;

Type oClassType = this.GetType(); //I'm calling this inside the class
PropertyInfo[] oClassProperties = oClassType.GetProperties();

foreach (PropertyInfo prop in oClassProperties)  //Loop thru properties works fine
{
    if (Nullable.GetUnderlyingType(prop.GetType()) == typeof(int))
        //should be integer type but prop.GetType() returns System.Reflection
    else if (Nullable.GetUnderlyingType(prop.GetType()) == typeof(string))
        //should be string type but prop.GetType() returns System.Reflection
    .
    .
    .
 }

首先,你不能在這里使用prop.GetType() - 這是PropertyInfo的類型 - 你的意思是prop.PropertyType

其次,嘗試:

var type = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;

無論它是可空的還是不可空的,這都可以工作,因為如果GetUnderlyingType不是Nullable<T> ,它將返回null

然后,在那之后:

if(type == typeof(int)) {...}
else if(type == typeof(string)) {...}

或替代方案:

switch(Type.GetTypeCode(type)) {
    case TypeCode.Int32: /* ... */ break;
    case TypeCode.String: /* ... */ break;
    ...
}

你快到了。 PropertyInfo類有一個屬性PropertyType ,它返回屬性的類型。 當您在PropertyInfo實例上調用GetType()時,您實際上只是獲取RuntimePropertyInfo ,它是您要反映的成員的類型。

因此,要獲取所有成員屬性的類型,您只需執行以下操作: oClassType.GetProperties().Select(p => p.PropertyType)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM