C# 我可以在创建对象之前计算属性吗?在构造函数中?
在创建对象之前,我可以计算类中属性的数量吗?我可以在构造器中完成吗C# 我可以在创建对象之前计算属性吗?在构造函数中?,c#,.net,properties,constructor,C#,.net,Properties,Constructor,在创建对象之前,我可以计算类中属性的数量吗?我可以在构造器中完成吗 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 } } 谢谢是
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
}
}
谢谢是的,您可以:
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();
}
}
正如BigYellowCactus所展示的那样,使用反射是可能的。但是没有必要每次都在构造函数中这样做,因为属性的数量永远不会改变 我建议在静态构造函数中执行此操作(每个类型只调用一次):
将此项用于类包含的属性计数
Type type = typeof(YourClassName);
int NumberOfRecords = type.GetProperties().Length;
通过反射,您可以检查类的属性:
typeof(ClassName).GetProperties().Length;
啊,这太容易了。Sry,我认为它更难——我创建了一个对象后,可以很容易地读取属性的数量,但在我没有对象之前,我认为它更难。THX运行时知道该类型,即使您没有该类型的实例。
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();
}
}
Type type = typeof(YourClassName);
int NumberOfRecords = type.GetProperties().Length;