我正在寫使用反射來獲取每個屬性名稱,並從類其價值的應用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)。 *備註*部分的解釋非常好。 –