如何在嵌套类上使用反射以获取值

huangapple go评论66阅读模式
英文:

How to use reflection on nested classes in order to get values

问题

这里是您要翻译的代码部分:

I have to an upper class with nested classes

    public class Preferences
	{
		public FunctionClass function { get; set; } = new FunctionClass();
		public class FunctionClass
		{
			public string programfolder { get; set; } = "";
			...
		}

		public LoggerClass logger { get; set; } = new LoggerClass();
		public class LoggerClass 
		{
			public string logFolder { get; set; } = "Log";
			...
		}

		public OptionClass options { get; set; } = new OptionClass();
		public class OptionClass
		{
			public bool showGraphics { get; set; } = true;
			...
		}

		public MqttSpSetupClass MqttSpSetup { get; set; } = new MqttSpSetupClass();
		public class MqttSpSetupClass
		{
			public string strAddress { get; set; } = "localhost";
			...
		}
	}


so I want reflection to cycle on all member of each inner class

    PropertyInfo[] props_Outer = typeof(IoAppPreferences).GetProperties();
	int counter = 0;
	foreach (PropertyInfo prop_Upper in props_Outer)
	{
		var sName_Outer = prop_Upper.Name;
		var val_Outer = props_Outer.GetValue(counter ++);
			
		PropertyInfo[] properties_Inner;
		switch (sName_Outer.ToUpper())
		{
			case "DIMS": properties_Inner = typeof(IoAppPreferences.DimsClass).GetProperties(); break;
		 ...	
		}

				 
		foreach (PropertyInfo prop_Inner in properties_Inner)
		{
			var sName = prop_Inner.Name;
			//prefs.function

			var sVal = prop_Inner.GetValue(val_Outer);<------ERROR

			switch (prop_Inner.Name.ToUpper())
			{
			 ...			
			}
		}
}

I get an error where I put the arrow. And the reason is that val_Outer is FunctionClass function while if I hardcode prefs.function it is ok. Of course, I can put a switch per each one, but my question is: is there a better way to solve it?

I have seen [this solution][1] but can't fit to my needs

这段代码主要涉及C#的反射和嵌套类操作。如果您需要更详细的解释或进一步的帮助,请随时告诉我。

英文:

I have to an upper class with nested classes

public class Preferences
{
	public FunctionClass function { get; set; } = new FunctionClass();
	public class FunctionClass
	{
		public string programfolder { get; set; } = "";
		...
	}

	public LoggerClass logger { get; set; } = new LoggerClass();
	public class LoggerClass 
	{
		public string logFolder { get; set; } = "Log";
		...
	}

	public OptionClass options { get; set; } = new OptionClass();
	public class OptionClass
	{
		public bool showGraphics { get; set; } = true;
		...
	}

	public MqttSpSetupClass MqttSpSetup { get; set; } = new MqttSpSetupClass();
	public class MqttSpSetupClass
	{
		public string strAddress { get; set; } = "localhost";
		...
	}
}

so I want reflection to cycle on all member of each inner class

PropertyInfo[] props_Outer = typeof(IoAppPreferences).GetProperties();
int counter = 0;
foreach (PropertyInfo prop_Upper in props_Outer)
{
	var sName_Outer = prop_Upper.Name;
	var val_Outer = props_Outer.GetValue(counter ++);
		
	PropertyInfo[] properties_Inner;
	switch (sName_Outer.ToUpper())
	{
		case "DIMS": properties_Inner = typeof(IoAppPreferences.DimsClass).GetProperties(); break;
	 ...	
	}

			 
	foreach (PropertyInfo prop_Inner in properties_Inner)
	{
		var sName = prop_Inner.Name;
		//prefs.function

		var sVal = prop_Inner.GetValue(val_Outer);<------ERROR

		switch (prop_Inner.Name.ToUpper())
		{
		 ...			
		}
	}

I get an error where I put the arrow. And the reason is that val_Outer is FunctionClass function while if I hardcode prefs.function it is ok. Of course, I can put a switch per each one, but my question is: is there a better way to solve it?

I have seen this solution but can't fit to my needs

答案1

得分: 1

你之所以出现错误,是因为val_Outer是错误的实例。您正试图从计数整数props_Outer.GetValue(counter++)中获取值。

如果您的目标是从嵌套类中获取属性值,您必须拥有Preferences对象的实例:

var appPreferences = new Preferences();
var propsOuter = appPreferences.GetType().GetProperties();

foreach (var po in propsOuter)
{
    var valueOuter = po.GetValue(appPreferences);
    Console.WriteLine($"{po.Name}");

    if (valueOuter == null) continue;

    var propsInner = valueOuter.GetType().GetProperties();
    foreach (var pi in propsInner)
    {
        var valueInner = pi.GetValue(valueOuter);
        Console.WriteLine($"{pi.Name}: {valueInner}");
    }
}

但是,如果您已经拥有对象实例,通过反射获取值就没有太大意义。

英文:

You got error because val_Outer is wrong instance. You are trying to get value out of counter integer props_Outer.GetValue(counter ++)

If your goal is to get property values from nested classes you must have instance of Preferences object:

    var appPreferences = new Preferences();
    var propsOuter = appPreferences.GetType().GetProperties();

    foreach (var po in propsOuter)
    {
        var valueOuter = po.GetValue(appPreferences);
        Console.WriteLine($"{po.Name}");

        if (valueOuter == null) continue;

        var propsInner = valueOuter.GetType().GetProperties();
        foreach (var pi in propsInner)
        {
            var valueInner = pi.GetValue(valueOuter);
            Console.WriteLine($"{pi.Name}: {valueInner}");
        }
    }

But getting values through reflection is pretty much useless if you already have object instance.

huangapple
  • 本文由 发表于 2023年2月16日 18:19:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75470806.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定