Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将数据从对象列表复制到C中的其他对象#_C#_.net - Fatal编程技术网

C# 将数据从对象列表复制到C中的其他对象#

C# 将数据从对象列表复制到C中的其他对象#,c#,.net,C#,.net,我的目标是减少代码并避免在我传递的对象列表变长时添加条件,随着项目的进展,它最多可以有100多个字段。我有一个MyObject类型的对象 public class MyObject { public string fininstId { get; set; } public string paymentMethod { get; set; } public string cardNumber { get; set; } public string cardExpi

我的目标是减少代码并避免在我传递的对象列表变长时添加条件,随着项目的进展,它最多可以有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; }
}
另一种是类型响应

public class Response
{
    public Response();

    public string Title { get; set; }
    public string Value { get; set; }
}
我需要将下面dataList中包含的所有数据复制到MyObject,因为我知道MyObject和dataList中的字段名称都是相同的

List dataList=newlist();
/*…正在此处填充数据列表*/
MyObject请求=新建MyObject();
foreach(数据列表中的变量项)
{
开关(项目名称)
{
案例“卡号”:
request.cardname=项目.Value;
打破
案例“信用卡到期日”:
request.cardExpiry=项目值;
打破
案例“cardCVC”:
request.cardCVC=项目值;
打破
案例“fininstId”:
request.fininstId=item.Value;
打破
案例“付款方式”:
request.paymentMethod=项目值;
打破
案例“AcctName”:
request.AcctName=item.Value;
打破
案例“密码”:
request.Password=item.Value;
打破
}
}
是否存在可以动态执行的方法

您可以使用和方法

例如:

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} );
或使用,


您可以使用反射来减少代码量,使其仅与标题字符串和属性名称匹配,但它不会执行得很好。您可以这样做。您需要考虑的条件是:“如果属性不存在怎么办?”和“如何处理类型转换?”。这两个问题都没有一个简单的答案。
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} );
var property = typeof(MyObject).GetProperty(item.Title);
property.SetValue(request, item.Value, null);