我正在尝试从一个子类中获取所有属性,然后设置值。但我不知道该怎么开始。我知道如何获取属性并设置值。但在子类上没有。
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; }
}
}
我怎样才能获得子类?并设置类的值?
编辑更新了我的代码。以便更好地理解。
我很困惑为什么我们要为此进行反思?
这能像一样简单吗
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; }
}
}