纔看到的這裏反射的幾個實例對象的屬性,但不能似乎讓他們爲我的確切問題工作...給我使用字符串
example of a solution I looked at
我的3個班...
public class Row
{
public string Cell1 = "cat";//{ get; set; }
public string Cell2 = "fish"; //{ get; set; }
public string Cell3 = "dog"; //{ get; set; }
}
public class Grid
{
public Row Row1 = new Row();
public Row Row2 = new Row();
public Row Row3 = new Row();
}
public class SetOfGrids
{
public Grid g1 = new Grid();
public Grid g2 = new Grid();
}
我怎樣才能獲得價值...
SetOfGrids sog = new SetOfGrids();
MessageBox.Show(sog.g1.Row1.Cell1);
使用getProperty本功能離子因爲我覺得可能工作的鏈接...
public Object GetPropValue(String name, Object obj) {
foreach (String part in name.Split('.')) {
if (obj == null) { return null; }
Type type = obj.GetType();
PropertyInfo info = type.GetProperty(part);
if (info == null) { return null; }
obj = info.GetValue(obj, null);
}
return obj;
}
我如何想獲得的價值...(我得到一個空異常錯誤。)
string PathToProperty = "sog.g1.Row1.Cell1";
string s = GetPropValue(PathToProperty, sog).ToString;
MessageBox.Show(s);
的結果應該是「CAT2 「
更新將行代碼更改爲建議的以下內容。
public class Row
{
public string Cell1 { get; set; }
public string Cell2 { get; set; }
public string Cell3 { get; set; }
public Row()
{
this.Cell1 = "cat";
this.Cell2 = "dog";
this.Cell3 = "fish";
}
}
剛剛嘗試過,仍然得到aSystem.NullReferenceException – user3755946
你可以發佈代碼嗎? – Divisadero
更新的主要帖子 – user3755946