我已经看到了几个反思的例子,但似乎无法让它们为我的确切问题而工作......
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";
}
}
答案 0 :(得分:2)
问题是你问方法GetProperty来获取字段,而不是属性。尝试将字段更改为属性或使用GetField方法。
答案 1 :(得分:2)
此:
using System;
using System.Linq;
using System.Net;
using System.Reflection;
namespace Test
{
public class Row
{
public string Cell1 { get; set; }
public string Cell2 { get; set; }
public string Cell3 { get; set; }
}
public class Grid
{
public Row Row1 { get; set; }
public Row Row2 { get; set; }
public Row Row3 { get; set; }
}
public class SetOfGrids
{
public Grid g1 { get; set; }
public Grid g2 { get; set; }
}
class Program
{
public static object GetPropValue(string name, object obj)
{
foreach (string part in name.Split('.'))
{
if (obj == null) { return null; }
var type = obj.GetType();
var info = type.GetProperty(part);
if (info == null) { return null; }
obj = info.GetValue(obj, null);
}
return obj;
}
public static void Main()
{
SetOfGrids sog = new SetOfGrids
{
g1 = new Grid { Row1 = new Row { Cell1 = "cat", Cell2 = "fish", Cell3 = "dog" }, Row2 = new Row { Cell1 = "cat", Cell2 = "fish", Cell3 = "dog" }, Row3 = new Row { Cell1 = "cat", Cell2 = "fish", Cell3 = "dog" } },
g2 = new Grid { Row1 = new Row { Cell1 = "cat", Cell2 = "fish", Cell3 = "dog" }, Row2 = new Row { Cell1 = "cat", Cell2 = "fish", Cell3 = "dog" }, Row3 = new Row { Cell1 = "cat", Cell2 = "fish", Cell3 = "dog" } }
};
string PathToProperty = "g1.Row1.Cell1";
object s = GetPropValue(PathToProperty, sog);
Console.WriteLine(s);
Console.ReadLine();
}
}
}
工作正常。请注意,我将所有字段都更改为实际属性,并删除了字符串的第一部分,因为“sog”。是变量名,而不是属性。