我的目标是减少代码并避免在我传递的对象列表变长时添加条件,随着项目的进展,最多可以有100多个字段。我有一个MyObject
类型的对象public class MyObject
{
public string fininstId { get; set; }
public string paymentMethod { get; set; }
public string cardNumber { get; set; }
public string cardExpiry { get; set; }
public string cardCVC { get; set; }
public string AcctName { get; set; }
public string Password { get; set; }
public string mode { get; set; }
}
另一个类型为Response
public class Response
{
public Response();
public string Title { get; set; }
public string Value { get; set; }
}
并且我需要将下面 dataList 中包含的所有数据复制到 MyObject ,因为知道两个字段的名称相同< em> MyObject 和 dataList 。
List<Response> dataList = new List<Response>();
/*...populating dataList here ...*/
MyObject request = new MyObject();
foreach (var item in dataList)
{
switch (item.Title)
{
case "cardNumber":
request.cardNumber = item.Value;
break;
case "cardExpiry":
request.cardExpiry = item.Value;
break;
case "cardCVC":
request.cardCVC = item.Value;
break;
case "fininstId":
request.fininstId = item.Value;
break;
case "paymentMethod":
request.paymentMethod = item.Value;
break;
case "AcctName":
request.AcctName = item.Value;
break;
case "Password":
request.Password = item.Value;
break;
}
}
无论如何它可以动态完成吗?
答案 0 :(得分:3)
您可以使用reflection和InvokeMember
方法
例如:
Response item = new Response();
item.Title = "Password";
item.Value = "value";
MyObject request = new MyObject();
request.GetType().InvokeMember(item.Title,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
Type.DefaultBinder, request, new[] {item.Value} );
或使用GetProperty
&amp; SetValue
var property = typeof(MyObject).GetProperty(item.Title);
property.SetValue(request, item.Value, null);