获取类中属性的值

时间:2014-04-03 06:39:58

标签: c# reflection

好的,所以我一直在互联网上寻找这个问题的解决方案。我认为我的头衔可能没有提供信息,所以有些背景。

我有以下课程:

public class foo { public string Name { get; set; } }
public class foo1 { public string Name { get; set; } }
public class foo2 { public string Name { get; set; } }
public class foo3 { public string Name { get; set; } }
public class foo4 { public string Name { get; set; } }
public class foo5 { public string Name { get; set; } }

public class goo 
{ 
   public string Desc { get; set; }
   public foo f { get; set; }
   public foo1 f1 { get; set; }
   public foo2 f2 { get; set; }
   public foo3 f3 { get; set; }
   public foo4 f4 { get; set; }
}

所以现在我的问题是,使用Reflection,如果只引用goo,我怎么能得到foo.Name的值。

正常的反思代码是:

goo g = new goo();
PropertyInfo pInfo = g.GetType().GetProperty("Name");
string Name = (string)pInfo.GetValue(g, null);

所以上面的代码就是你如何从goo类中获取属性。但是现在你如何获得foo.Desc的价值?

我尝试了以下不起作用:

goo g = new goo();
PropertyInfo pInfo = g.GetType().GetProperty("f");
PropertyInfo pInfo2 = pInfo.PropertyType.GetProperty("Desc");
string Name = (string)pInfo2.GetValue(pInfo.PropertyType, null);

不幸的是我得到了一个不匹配的对象错误,我可以理解,因为我试图使用属性类型而不是foo类的实际实例。我还尝试了一种方法来从propertyinfo实例化一个对象,但是如果有办法那么它就会让我失望。我可以这样做:

goo g = new goo();
PropertyInfo propInfo = g.GetType().GetProperty("f");
object tmp;

propInfo.SetValue(g, Convert.ChangeType(new foo(), propInfo.PropertyType), null);
tmp = g.f;

这有效但除了必须对类进行硬编码之外,那就是创建一个新实例,因此现在对我有用。

正如我所说,我一直在寻找解决方案。我发现的一切基本上都是“获得一个类的属性的价值”主题的变体,但没有任何关于更深层次的更多。

有人可以帮忙吗?这甚至是可能的,因为我真的想远离硬编码。

编辑:我编辑了课程,以更准确地表示我正在使用的内容。根据下面的评论,我从数据库中获取foo实例的名称,这就是我使用Reflection或者想使用Reflection而不是硬编码30+ switch语句的原因。

编辑:我也不知道在运行时哪个foo类将填充数据。每个foo类都不同。与我的每个foo类都有字符串属性的示例不同,在我的项目中,每个类都有不同的设计,它反映了数据库。

编辑:所以Ulugbek Umirov给出了答案。我只是没有立刻看到它。在我的实施之下,以便将来可能帮助其他人。

foreach (PropertyInfo pInfo in _standard.GetType().GetProperties())
{
    if (_fullDataModel.ClassDefinitions.Contains(pInfo.Name))
    {
        PropertyInfo _std_pinfo = _standard.GetType().GetProperty(pInfo.Name);
        object g = _std_pinfo.GetValue(_standard, null);

        PropertyInfo props = g.GetType().GetProperty("showMe");
        bool showMe = (bool)props.GetValue(g, null);

        if (showMe)
        {
            string tblName = _fullDataModel.ClassDefinitions[pInfo.Name].                   PropertyGroupDefinitions.Where(p => p.TransactionsTable != true).First().Token;

            //  Use tblName to build up a dataset
        }
    }
}

这正是我想要的。 谢谢。

1 个答案:

答案 0 :(得分:1)

根据您当前的代码,您可以执行以下操作:

goo g = new goo();
g.f = new foo { Name = "Hello" };

PropertyInfo pInfo = g.GetType().GetProperty("f");
object f = pInfo.GetValue(g);
PropertyInfo pInfo2 = f.GetType().GetProperty("Name");
string name = (string)pInfo2.GetValue(f);

您也可以设置任意属性:

goo g = new goo();

PropertyInfo pInfo = g.GetType().GetProperty("f");
object f = Activator.CreateInstance(pInfo.PropertyType);
PropertyInfo pInfo2 = f.GetType().GetProperty("Name");
pInfo2.SetValue(f, "Hello");
pInfo.SetValue(g, f);
相关问题