【问题标题】:C# GetValue of PropertyInfo with SubClasses带有子类的 PropertyInfo 的 C# GetValue
【发布时间】:2017-01-05 10:40:36
【问题描述】:

首先,对不起我的英语不好...希望你能明白我想说的话。

我有一个小代码问题,我需要获取类属性的值。 (这不是我的完整项目,而是我想做的概念。用这个简单的代码,我被阻止了。)

有代码:(此示例可以正常工作。)

using System;
using System.Reflection;

class Example
{
    public static void Main()
    {
        test Group = new test();
        BindingFlags bindingFlags = BindingFlags.Public |
                                    BindingFlags.NonPublic |
                                    BindingFlags.Instance |
                                    BindingFlags.Static;
        Group.sub.a = "allo";
        Group.sub.b = "lol";

        foreach (PropertyInfo property in Group.GetType().GetField("sub").FieldType.GetProperties(bindingFlags))
        {
            string strName = property.Name;
            Console.WriteLine(strName + " = " + property.GetValue(Group.sub, null).ToString());
            Console.WriteLine("---------------");
        }
    }
}

public class test
{
    public test2 sub = new test2();
}

public class test2
{
    public string a { get; set; }
    public string b { get; set; }
}

但我想用动态访问替换Group.sub(比如foreachGetField(Var) 工作)。我尝试了很多组合,但我没有找到任何解决方案。

property.GetValue(property.DeclaringType, null)

property.GetValue(Group.GetType().GetField("sub"), null)

property.GetValue(Group.GetType().GetField("sub").FieldType, null)

所以我想你明白了。我想动态地给出对象Group.sub 的实例。因为,在我的整个项目中,我有很多子类。

有什么想法吗?

【问题讨论】:

    标签: c# foreach getproperty getvalue


    【解决方案1】:

    您已经使用Group.GetType().GetField("sub") 访问sub 字段,您需要获取它的值并保留它:

    FieldInfo subField = Group.GetType().GetField("sub");
    
    // get the value of the "sub" field of the current group
    object subValue = subField.GetValue(Group);
    foreach (PropertyInfo property in subField.FieldType.GetProperties(bindingFlags))
    {
        string strName = property.Name;
        Console.WriteLine(strName + " = " + property.GetValue(subValue, null).ToString());    
    }
    

    【讨论】:

    • 感谢 C:Evenhuis 的回复。这正是我想做的!我已经测试过了,它可以工作。要对添加级别做同样的事情,我们可以这样做吗? FieldInfo subField = Group.GetType().GetField("sub");对象 subValue = subField.GetValue(Group); FieldInfo subField2 = Group.GetType().GetField("sub").FieldType.GetField("sub2");对象 subValue2 = subField2.GetValue(subValue);还是存在更快的方法?
    • 是的,你可以,你可以“坚持”以前的结果——即。要获取“sub2”字段信息,您不必从Group.GetType()... 开始;你可以使用subField.FieldType.GetField("sub2")
    • 谢谢 C.Evenhuis。我就是这样做的 =)
    猜你喜欢
    • 1970-01-01
    • 2011-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多