开发者

How can I use reflection to map a list<objects> that include enum values

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 开发者_如何学PythonpartProperties, 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.


var partNames=Enum.GetNames(typeof(PartToModify));
var parts = from pi in partObj.GetType.GetProperties()
            where partNames.Contains(pi.Name)
            select new UpdatePart { 
                         PartToModify = (partToModify)Enum.Parse(typeof(PartToModify),pi.Name),
                         NewValue=pi.GetValue(partObj,null)
                       };
foreach (var part in parts) UpdateList.Add(part);


I'm not completely sure what you are trying to do here but to find a value of an enum by it's string value you could use Enum.Parse or Enum.TryParse. You could do something like this:

PartToModify result;
if (Enum.TryParse<PartToModify>("Engine", true, out result))
{
  /* found a match. It's in result */
}

The 2nd true parameter tells it to ignore case. so you could match all of "Engine", "engine", "ENGINE", etc..

You could also go the other way around and just find all names that are in the enum by using

string[] myNames = Enum.GetNames(typeof(PartToModify));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜