![](/img/trans.png)
[英]How do I get the properties from a subclass when I have the class but subclass name as a string
[英]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.