繁体   English   中英

如何根据名称获取所有子类属性

[英]How do I get all subclass properties based on name

我有以下结构:

 public class A
 {
    public A1Type A1{get;set;}
    public A2Type A2{get;set;}
    public A3Type A3{get;set;}
  }
  public A1Type
  {
    public string B1{get;set;}
    public string B2{get;set;}
  }

和A1Type类似的还有A2Type和A3Type。我有一个更复杂的结构。

我收到一个字符串参数“A1Type”,我需要从 A 获取子类 A1Type 及其值。 有人可以帮我吗?

这可能会做你想要的:

class Program
{
    static void Main(string[] args)
    {
        var a = new A()
        {
            A1 = new A1Type() { B1 = "A1Type B1 prop value", B2 = "A1Type B2 prop value" },
            A2 = new A2Type() { B1 = "A2type B1 prop value", B2 = "A2Type B2 prop value" },
            A3 = new A3Type() { B1 = "A3Type B1 prop value", B2 = "A3Type B2 prop value" }
        };
        ListPropertyValuesOf("A1Type", a);
        ListPropertyValuesOf("A2Type", a);
        ListPropertyValuesOf("A3Type", a);
    }

    static void ListPropertyValuesOf(string propName, A classA)
    {
        // get all properties of classA object
        var props = classA.GetType().GetProperties();
        foreach (var prop in props)
        {
            if (prop.PropertyType.Name == propName)
            {
                // get the specific sub-type object on classA
                var subClassA = classA.GetType().GetProperty(prop.Name).GetValue(classA);

                // loop each of the properties on subClassA and write its value
                foreach (var subProp in subClassA.GetType().GetProperties())
                    Console.WriteLine(subProp.GetValue(subClassA));
            }
        }
    }
}

public class A
{
    public A1Type A1 { get; set; }
    public A2Type A2 { get; set; }
    public A3Type A3 { get; set; }
}
public class A1Type
{
    public string B1 { get; set; }
    public string B2 { get; set; }
}

public class A2Type
{
    public string B1 { get; set; }
    public string B2 { get; set; }
}

public class A3Type
{
    public string B1 { get; set; }
    public string B2 { get; set; }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM