Kev*_*oss 5 c# foreach getproperty getvalue
首先,抱歉我的英语不好...我希望你能理解我想说的话。
我有一个小代码问题,我需要获取类属性的值。(这不是我的完整项目,而是我想做的事情的概念。用这个简单的代码,我被阻止了。)
有代码:(此示例工作正常。)
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; }
}
Run Code Online (Sandbox Code Playgroud)
但我想,以取代Group.sub与动态访问(如foreach与GetField(Var)它的工作原理)。我尝试了很多组合,但我还没有找到任何解决方案。
property.GetValue(property.DeclaringType, null)
Run Code Online (Sandbox Code Playgroud)
或者
property.GetValue(Group.GetType().GetField("sub"), null)
Run Code Online (Sandbox Code Playgroud)
或者
property.GetValue(Group.GetType().GetField("sub").FieldType, null)
Run Code Online (Sandbox Code Playgroud)
所以我想你明白了。我想Group.sub动态地给出对象的实例。因为,在我的完整项目中,我有很多子类。
有任何想法吗?
您已经在sub使用 访问该字段Group.GetType().GetField("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());
}
Run Code Online (Sandbox Code Playgroud)