2012-12-11 48 views
2

我有這樣定義的類:如何知道一個類的屬性的類型是定製

public class Company 
{ 
    public Int32 OrganisationID {get;set;} 
    public CompanyStatus OrganisationStatus {get;set;} 
    // note that CompanyStatus is my custom type 
} 

然後我將代碼編譯成Entity.dll。當我使用下面的代碼時,我得到((System.Reflection.MemberInfo)(properties[1])).NameCompanyStatus。我如何判斷它是否爲自定義類型,因爲我正在動態讀取所有屬性?

Assembly objAssembly = Assembly.LoadFrom(@"Entities.dll"); 

var types1 = objAssembly.GetTypes(); 

foreach (Type type in types1) 
{ 
    string name = type.Name; 
    var properties = type.GetProperties(); // public properties 
    foreach (PropertyInfo objprop in properties) 
    { 
     // Code here 
    } 
} 
+0

你是什麼意思「自定義類型」?你的意思是,如果它是BCL(基類庫)的一部分 – Tigran

+0

@Tigran我想捕獲除原始類型以外的其他東西。如果我有屬性列表我想提取類型即CustomTypeA –

回答

4

使用IsPrimitive屬性來判斷一個屬性的類型不是基本類型或字符串

if(objprop.PropertyType.IsPrimitive || objprop.PropertyType == typreof(string)) 

MSDN

的基本類型是布爾,字節,爲SByte ,Int16,UInt16,Int32,UInt32,Int64,UInt64,IntPtr,UIntPtr,Char,Double和Single。

您可能還需要檢查陣列原始類型等。要看到,如果該類型包裝另一個使用類型:

if(objprop.PropertyType.HasElementType) 
    var t2 = objprop.PropertyType.GetElementType(); 
+0

謝謝。但是,如果我的財產是公開的如何處理清單名單辦公室。並且我想將Office提取爲(properties [3] .PropertyType).FullName給出System.Collections.Generic.List'1 [[Entities.eOffice,Entities,Version = 2.2.0.0,Culture = neutral,PublicKeyToken = null]] –

+0

你想知道_actual type_還是僅僅是一個自定義類型?這是一個不同的問題。 –

+0

是的,正確的第一個問題已經解決了謝謝你。現在我想知道它的實際類型((System.Reflection.MemberInfo)(properties [3] .PropertyType))。Name返回「List'1」 –

相關問題