我想通过Reflection设置对象的属性,值为type string.所以,举个例子,假设我有Ship一个属性为的类Latitude,它是一个double.
这是我想做的事情:
Ship ship = new Ship();
string value = "5.5";
PropertyInfo propertyInfo = ship.GetType().GetProperty("Latitude");
propertyInfo.SetValue(ship, value, null);
Run Code Online (Sandbox Code Playgroud)
这样就抛出了ArgumentException:
"System.String"类型的对象无法转换为"System.Double"类型.
如何将值转换为正确的类型,基于propertyInfo?
给出以下对象:
public class Customer {
public String Name { get; set; }
public String Address { get; set; }
}
public class Invoice {
public String ID { get; set; }
public DateTime Date { get; set; }
public Customer BillTo { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我想用反射Invoice来获得一个Name属性Customer.这就是我所追求的,假设这段代码可行:
Invoice inv = GetDesiredInvoice(); // magic method to get an invoice
PropertyInfo info = inv.GetType().GetProperty("BillTo.Address");
Object val = info.GetValue(inv, null);
Run Code Online (Sandbox Code Playgroud)
当然,由于"BillTo.Address"不是Invoice该类的有效属性,因此失败.
所以,我尝试编写一个方法将字符串拆分成句点,并遍历对象寻找我感兴趣的最终值.它可以正常工作,但我对它并不完全满意:
public Object GetPropValue(String …Run Code Online (Sandbox Code Playgroud) 编辑:最初我打算使用AutoMapper来实现我的目标,但我必须了解到AutoMapper并非旨在以这种方式工作。它使您可以创建配置文件,但就我而言(完全可配置),对于每种参数组合,我都需要一个配置文件,因此我想出了一种自己的方法,请参见答案。
从AutoMapper Wiki,我学会了创建一个简单的映射,例如
Mapper.CreateMap<CalendarEvent, CalendarEventForm>().ForMember(dest => dest.Title, opt => opt.MapFrom(src => src.Title));
Mapper.CreateMap<CalendarEvent, CalendarEventForm>().ForMember(dest => dest.EventDate, opt => opt.MapFrom(src => src.EventDate.Date));
Mapper.CreateMap<CalendarEvent, CalendarEventForm>().ForMember(dest => dest.EventHour, opt => opt.MapFrom(src => src.EventDate.Hour));
Mapper.CreateMap<CalendarEvent, CalendarEventForm>().ForMember(dest => dest.EventMinute, opt => opt.MapFrom(src => src.EventDate.Minute));
Run Code Online (Sandbox Code Playgroud)
对于两个类
public class CalendarEvent
{
public DateTime EventDate;
public string Title;
}
public class CalendarEventForm
{
public DateTime EventDate { get; set; }
public int EventHour { get; set; }
public int EventMinute { get; set; }
public string Title …Run Code Online (Sandbox Code Playgroud)