有時我想知道某個對象是否有我正在查找的屬性,但有時對象具有很多屬性,並且可能需要一些時間才能找到它。這將是很好,如果我可以編寫一個函數,將找到所有的屬性和它的價值在一個字符串,然後我可以粘貼該字符串記事本爲例,並尋找我正在尋找與記事本查找功能的價值。到目前爲止,我有這樣的事情:查找對象的所有屬性和子屬性
public void getAllPropertiesAndSubProperties(System.Reflection.PropertyInfo[] properties)
{
foreach (var a in properties)
{
//MessageBox.Show(a.ToString());
// do something here to test if property a is the one
// I am looking for
System.Reflection.PropertyInfo[] temp = a.GetType().GetProperties();
// if property a has properties then call the function again
if (temp.Length > 0) getAllPropertiesAndSubProperties(temp);
}
}
編輯我曾經工作過的問題:
到目前爲止,我已經添加下面的代碼。我可以將任何我想要的對象傳遞給以下方法,並可以看到所有屬性。我無法查看屬性
![public void stackOverex(dynamic obj)
{
// this is the string where I am apending all properties
string stringProperties = "";
Type t = obj.GetType();
List<PropertyInfo> l = new List<PropertyInfo>();
while (t != typeof(object))
{
l.AddRange(t.GetProperties());
t = t.BaseType;
var properites = t.GetType().GetProperties();
foreach (var p in properites)
{
string val = "";
try
{
val = obj.GetType().GetProperty(p.Name).GetValue(obj, null).ToString();
}
catch
{
}
stringProperties += p.Name + " - " + val + "\r\n";
}
}
MessageBox.Show(stringProperties);
}
呀Visual Studio調試器是偉大的,但看一個對象可以有多少屬性具有的值。我實際上正在尋找gridViewColumnHeader的indexSomething屬性我不記得我以前使用過的確切名稱。我有一個事件,當一個列被點擊時觸發,我想知道索引不是名稱「列號2?或3被點擊」。我知道我可以得到它的名字,但是如果我可以實現這個調試器功能,它會很好。看看下面的圖片有多複雜。
問題是什麼? – Justin 2011-05-11 03:12:34
而你的問題是?這可能很容易以無限循環結束。 – 2011-05-11 03:13:08
你有沒有使用過Visual Studio調試器? – mellamokb 2011-05-11 03:14:43