使用 Reflection.PropertyInfo
using Reflection.PropertyInfo
我需要遍历对象的属性并为每个属性设置 2 个值。
比如你有车class:
Class car
Property Wheel1 As Wheel
Property Wheel2 As Wheel
Property Wheel3 As Wheel
Property Wheel4 As Wheel
End Class
每个轮子都有一组属性:
Class Wheel
Property size As Integer
Property type As Integer
End Class
有没有办法动态循环一个有轮子的对象并将其所有轮子设置为 size=5 和 type=1。
这是我试图让它工作时遇到的问题:
Dim ThisCar As New car
Dim Wheels() As Reflection.PropertyInfo = ThisCar.GetType().GetProperties()
Dim i As Integer = 0
Do Until i = Wheels.Count
Dim TempWheel As Reflection.PropertyInfo = Wheels(i)
Dim WheelProps() As Reflection.PropertyInfo = TempWheel.GetType().GetProperties()
i = i + 1
Loop
WheelProps
不是所需的属性...
你应该使用 TempWheel.PropertyType() 而不是 TempWheel.GetType()
或者你只是像这样设置轮子:
foreach(var pInfo in typeof(car).GetProperties()
{
if(pInfo.PropertyType == typeof(Wheel))
{
// Get the value of existing wheel
var wheel = (Wheel)pInfo.GetValue(ThisCar);
Console.WriteLine(wheel.size);
Console.WriteLine(wheel.type);
// Set the value of wheel
wheel.size = 5;
wheel.type = 1;
//pInfo.SetValue(ThisCar, new Wheel() {size = 5, type = 1}, null);
}
}
但是为什么不实现带有 List<Wheel>
的汽车呢?
我需要遍历对象的属性并为每个属性设置 2 个值。
比如你有车class:
Class car
Property Wheel1 As Wheel
Property Wheel2 As Wheel
Property Wheel3 As Wheel
Property Wheel4 As Wheel
End Class
每个轮子都有一组属性:
Class Wheel
Property size As Integer
Property type As Integer
End Class
有没有办法动态循环一个有轮子的对象并将其所有轮子设置为 size=5 和 type=1。
这是我试图让它工作时遇到的问题:
Dim ThisCar As New car
Dim Wheels() As Reflection.PropertyInfo = ThisCar.GetType().GetProperties()
Dim i As Integer = 0
Do Until i = Wheels.Count
Dim TempWheel As Reflection.PropertyInfo = Wheels(i)
Dim WheelProps() As Reflection.PropertyInfo = TempWheel.GetType().GetProperties()
i = i + 1
Loop
WheelProps
不是所需的属性...
你应该使用 TempWheel.PropertyType() 而不是 TempWheel.GetType() 或者你只是像这样设置轮子:
foreach(var pInfo in typeof(car).GetProperties()
{
if(pInfo.PropertyType == typeof(Wheel))
{
// Get the value of existing wheel
var wheel = (Wheel)pInfo.GetValue(ThisCar);
Console.WriteLine(wheel.size);
Console.WriteLine(wheel.type);
// Set the value of wheel
wheel.size = 5;
wheel.type = 1;
//pInfo.SetValue(ThisCar, new Wheel() {size = 5, type = 1}, null);
}
}
但是为什么不实现带有 List<Wheel>
的汽车呢?