2012-07-24 65 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; 
相关问题