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

mir*_*iri 6 .net c# constructor properties

在创建对象之前,我可以计算类中的属性数量吗?我可以在构造函数中执行此操作吗?

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
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢

slo*_*oth 13

是的你可以:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)


Jul*_*anR 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();
    }
}
Run Code Online (Sandbox Code Playgroud)