Using Reflection.PropertyInfo
I need to go through the properties of an object and set the values to 2 for each property.
for example you have a car class:
Class car
Property Wheel1 As Wheel
Property Wheel2 As Wheel
Property Wheel3 As Wheel
Property Wheel4 As Wheel
End Class
and each wheel has a set of properties:
Class Wheel
Property size As Integer
Property type As Integer
End Class
is there a way to dynamically scroll an object with wheels and set all of its wheels to size = 5 and type = 1.
this is where i got stuck trying to get it to work:
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
are not properties from the wheel as needed ...
+3
source to share
1 answer
You should use TempWheel.PropertyType () and not just TempWheel.GetType (), or just set the Wheel:
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);
}
}
But why not implement a car with List<Wheel>
?
+2
source to share