[英]how can I get subclass properties and set the value?
我正在嘗試從子 class 獲取所有屬性,然后設置值。 但我不知道如何開始。 我知道如何獲取屬性並設置值。 但在子 class 上沒有。
public class Program {
public static void Main(string[] args) {
object[] Response = new object[] {
new Cars() {
Details = new Details() {
CanDrive = true,
ID = 123,
IsPolice = true
},
Name = "test",
Speed = 100
}
};
var Result = Test <Cars> (Response);
Console.WriteLine(Result.Speed);
}
private static T Test <T> (object[] Obj) {
var Instance = CreateInstance <T> ();
foreach(var Ob in Obj) {
PropertyInfo[] C = Ob.GetType().GetProperties();
foreach(var n in C) {
PropertyInfo[] P = typeof(T).GetProperties();
foreach(PropertyInfo Val in P) {
if (n.Name == Val.Name) V
Val.SetValue(Instance, n.GetValue(Ob));
}
}
}
return Instance;
}
private static T CreateInstance <T>() => Activator.CreateInstance<T>();
public class Cars {
public int Speed { get; set; }
public string Name { get; set; }
public Details Details { get; set; }
}
public class Details {
public int ID { get; set; }
public bool CanDrive { get; set;}
public bool IsPolice { get; set; }
}
}
我怎樣才能得到子類? 並設置 class 的值?
編輯更新了我的代碼。 為了更好地理解。
我很困惑為什么我們要一直為此進行反思?
這可以簡單到
var car = new Car();
car.Details = new Details()
{
CanDrive = true,
ID = 42,
IsPolice = false
};
public class Program
{
public static void Main(string[] args)
{
var CarInstance = CreateInstance<Cars>();
PropertyInfo[] P = typeof(Cars).GetProperties();
foreach (PropertyInfo Car in P)
{
if(Car.Details.IsPolice) //Access properties of subclass using the name of the property, which is "Details"
Car.SetValue(CarInstance, 12345);
if(Car.Name == "ID")
Car.SetValue(CarInstance, 12345);
}
}
private static T CreateInstance<T>() => Activator.CreateInstance<T>();
public class Cars
{
public int Speed { get; set; }
public string Name { get; set; }
public Details Details { get; set; }
}
public class Details
{
public int ID { get; set; }
public bool CanDrive { get; set; }
public bool IsPolice { get; set; }
}
}
這個微小的差異可能有助於消除一些混淆:
public class Program
{
public static void Main(string[] args)
{
var CarInstance = CreateInstance<Cars>();
PropertyInfo[] P = typeof(Cars).GetProperties();
foreach (PropertyInfo Car in P)
{
if(Car.ThisCarDetails.IsPolice) //Access properties of subclass using the name of the property, which is "ThisCarDetails"
Car.SetValue(CarInstance, 12345);
if(Car.Name == "ID")
Car.SetValue(CarInstance, 12345);
}
}
private static T CreateInstance<T>() => Activator.CreateInstance<T>();
public class Cars
{
public int Speed { get; set; }
public string Name { get; set; }
public Details ThisCarDetails { get; set; }
}
public class Details
{
public int ID { get; set; }
public bool CanDrive { get; set; }
public bool IsPolice { get; set; }
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.