我正在写使用反射来获取每个属性名称,并从类其价值的应用System.Windows.Forms.SystemInformation
我当前的代码是从这个线程的代码段:C#遍历SystemInformation但与它的属性麻烦电源状态,
How can you loop over the properties of a class?
马克的答案可能是最好的,但对我来说这太复杂了,因为这是我第一次做反思,他的技能太高了。
所以这是我第一次。
foreach (PropertyInfo prop in typeof(System.Windows.Forms.SystemInformation).GetProperties())
{
richTextBox1.AppendText(prop.Name + "\t\t" + prop.GetValue(null, null)
}
但我不知道如何遍历类powerstatus
的属性循环。 我想过检查当前的道具是否是原始类型。 如果不是,我会递归地调用上面的函数。 所以它看起来像这样:
private void readProperties(Type T, int indent)
{
//var x = System.Windows.Forms.SystemInformation.ActiveWindowTrackingDelay;
foreach (PropertyInfo prop in T.GetProperties())
{
for (int x = 0; x < indent; x++)
richTextBox1.AppendText("\t");
richTextBox1.AppendText(prop.Name + "\t\t" + prop.GetValue(null, null) +"\n");
if (!prop.PropertyType.IsPrimitive)
readProperties(prop.PropertyType, indent+1);
//System.Windows.Forms.PowerStatus PS = new PowerStatus();
}
}
但现在我得到异常: “死nicht-statische了Methode erfordert EIN ZIEL” 翻译是这样的: “非静态方法需要一个目标”
第一次递归调用函数时抛出异常。 属性是primaryMonitorSize,它的类型为Size
。恕我直言,这与我解析类型Size
而不是System.Windows.Forms.SystemInformation.primaryMonitorSize
的事实有关,以便我知道实际的类型,但不知道我的程序的哪个成员,因为它也可能是winForm的大小。
那么我该如何解决这个问题?我感谢每一个建设性的批评。
@编辑:这是一个MSDN的例子。但它看起来不漂亮。 http://msdn.microsoft.com/de-de/library/system.windows.forms.systeminformation.powerstatus.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2
谢谢你,但你的代码的另一个问题。什么是逻辑或在GetProperties完成。只分离静态和非静态属性。公众和非公众也有点混淆 –
看看MS文章的方法:[Type.GetProperties方法(BindingFlags)](http://msdn.microsoft.com/en-us/library/kyaxdd3x。 ASPX)。 *备注*部分的解释非常好。 –