2012-07-24 63 views

回答

11

是的,你可以:

class MyClass 
{ 
    public string A { get; set; } 
    public string B { get; set; } 
    public string C { get; set; } 

    public MyClass() 
    { 
     int count = this.GetType().GetProperties().Count(); 
     // or 
     count = typeof(MyClass).GetProperties().Count(); 
    } 
} 
+0

啊那是多麼容易它是。 Sry,我認爲它更難 - 認爲在我創建一個對象之後,但在沒有一個對象之前我很容易理解它的性質。 Thx – miri 2012-07-24 14:21:34

+0

即使您沒有它的實例,該類型對運行時也是已知的。 – sloth 2012-07-24 14:23:52

3
public MyClass() 
{ 
    int count = GetType().GetProperties().Count(); 
} 
+0

:(愚蠢的capcha輸入 – 2012-07-24 14:20:14

5

這是可能使用反射作爲BigYellowCactus顯示。但是沒有必要每次都在構造函數中執行此操作,因爲屬性的數量永遠不會更改。

我建議在靜態構造函數做這件事(被稱爲每個類型只有一次):

class MyClass 
{ 
    public string A{ get; set; } 
    public string B{ get; set; } 
    public string C{ get; set; } 

    private static readonly int _propertyCount; 

    static MyClass() 
    { 
     _propertyCount = typeof(MyClass).GetProperties().Count(); 
    } 
} 
0

用這個數沒有屬性的類包含

Type type = typeof(YourClassName); 
int NumberOfRecords = type.GetProperties().Length; 
相關問題