If I have an object
public class Car {
public List<UpdatePart> updatePartList {get; set;}
}
public class UpdatePart {
public PartToModify PartToModify {get; set;}
public string NewValue {get;set}
}
And the PartToModify is an enum:
public enum PartToModify {
Engine,
Tire,
}
And I have a Part object:
public class Part {
public string Engine {get;set;}
public string Tire {get;set;}
public decimal price {get;set;}
}
How can I use reflection and for every property on Part that matches a enum in PartToModify, create a new UpdatePart object and select the correct enum where PartToModify == Part.Property and assigns the UpdatePart.NewValue the value of Part.Property.
I would something like:
var partProperties = partObj.GetType().GetProperties();
foreach (var property on updatePartProperties) {
UpdatePartList.Add(MapProperties(partProperties, part));
}
public UpdatePart MapProperties(PropertyInfo partProperties, Part partObj){
//pseudo code
var updatePart = new UpdatePart();
foreach(var property on partProperties) {
if (property.Name == <iterate through enum values until one is found>)
updatePart.PartToModify = PartToModify.<somehow select value that matches property.name>
updatePart.NewValue = property.GetValue(partObj, null);
}
return updatePart;
}
Obviously you get the jiff of what I am trying to do, any thoughts? And no, this is not a school project. The whole “car” example was the quickest closest example I came up with to the actual objects, since I didn’t want to just write out what I was trying to accomplish, wanted to provide an example.
1 Answer