【问题标题】:How do I get all subclass properties based on name如何根据名称获取所有子类属性
【发布时间】:2019-11-20 13:58:41
【问题描述】:

我有以下结构:

 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 及其值。 有人可以帮我解决这个问题吗?

【问题讨论】:

  • 为避免使用反射或高维护映射,您是否考虑使用Dictionary<string, object>Dictionary<string, ABaseType>。例如,您可以只返回 A["A1Type"]。

标签: c# class generics xml-deserialization


【解决方案1】:

这可能会做你想做的事:

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; }
}

【讨论】:

    猜你喜欢
    • 2011-07-27
    • 2011-02-04
    • 2010-10-14
    • 2020-08-21
    • 1970-01-01
    • 2010-09-14
    • 1970-01-01
    相关资源
    最近更新 更多