我可以在创建对象之前计算类中的属性数量吗?我可以在构造函数中完成吗?
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
}
}
谢谢
答案 0 :(得分:12)
是的,你可以:
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();
}
}
答案 1 :(得分: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();
}
}
答案 2 :(得分:3)
public MyClass()
{
int count = GetType().GetProperties().Count();
}
答案 3 :(得分:0)
使用此功能计算您的类包含的属性数
#nav {
width:95%;
font-family: Tahoma;
font: bold;
color: #00FFFF;
float: none;
}
.form{
height:50px;
position: absolute;
text-align:center;
font-size:16px;
font-family:Candara;
color:#00FFFF;
background-color: transparent;
min-width: 160px;
float:left-wards;
}
.dropbtn {
background-color: transparent;
color: #00FFFF;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: transparent;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index:1000;
}
.dropdown-content a {
color: #00FFFF;
padding: 6px 16px;
text-decoration: none;
display: block;
z-index:1000;
}
.dropdown-content a:hover {background-color: transparent}
.dropdown:hover .dropdown-content {
display: block;
z-index:1000;
}
.dropdown:hover .dropbtn {
background-color: transparent;
}
答案 4 :(得分:0)
通过反射可以检查类的属性:
typeof(ClassName).GetProperties().Length;