【问题标题】:Can I count properties before I create an object? In the constructor?我可以在创建对象之前计算属性吗?在构造函数中?
【发布时间】:2012-07-22 21:16:09
【问题描述】:

我可以在创建对象之前计算类中的属性数量吗?可以在构造函数中做吗?

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

    public MyClass()
    {
        int count = //somehow count properties? => 3
    }
}

谢谢

【问题讨论】:

    标签: c# .net properties constructor


    【解决方案1】:

    通过反射可以检查类的属性:

    typeof(ClassName).GetProperties().Length;
    

    【讨论】:

      【解决方案2】:

      使用它来计算你的类包含的属性数

      Type type = typeof(YourClassName);
      int NumberOfRecords = type.GetProperties().Length;
      

      【讨论】:

        【解决方案3】:

        是的,您可以:

        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();
            }
        }
        

        【讨论】:

        • 啊,就是这么简单。对不起,我认为它更难 - 在我创建一个对象之后,我认为它很容易读取属性的数量,但在我没有对象之前,我认为它更难。谢谢
        • 该类型对于运行时来说是已知的,即使您没有它的实例。
        【解决方案4】:

        正如 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();
            }
        }
        

        【讨论】:

          【解决方案5】:
          public MyClass()
          {
              int count = GetType().GetProperties().Count();
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-06-30
            • 2010-10-22
            • 1970-01-01
            • 2019-07-11
            • 1970-01-01
            相关资源
            最近更新 更多