我有一个第三方dll。当我检索一些数据时,我会以以下格式返回:
var getData = getSomeData();
var customers = getData.Customers;
customers
具有 IEnumerable<IGenericCustomer>
的类型,但内部有多个条目。因此,在调试模式下的客户内部,我看到了这一点:
[0] "customerName" ("Text")
[1] "customerId" ("Text")
[2] "customerTitle" ("Text")
[3] "customerGender" ("Text")
扩展每一个都会提供更多的属性和信息。为了检索一个值,我目前可以做类似的事情
var customerName = customers.FirstOrDefault(c=> c.Property == "customerName").ToString();
有没有一种方法可以让我解析
IEnumerable<GenericCustomer>
并且可以将 customerName、Id、Title、Gender 作为单值属性添加到对象中,而不是使用 foreach
循环与对象并将每个值分配给它自己的属性(如果将来他们添加更多属性,这意味着我必须更新此过程?
我四处寻找这个问题,但我的问题的模糊性并没有给我想要实现的目标带来很多结果,所以希望有人有一个很好的简单例子供我遵循。
编辑1
这就是
IGenericCustomer
的样子(我将其更改为界面)。有很多类似模式的属性。我在下面使用了 Property
来与上面使用的保持一致
public interface IGenericCustomer
{
string Property {get;}
....
....
}
我会尝试评论中发布的其他建议
您可以创建一个类来保存您的数据:
class Customer
{
public string CustomerId { get; set; }
public string CustomerName { get; set; }
public string CustomerTitle { get; set; }
public string CustomerGender { get; set; }
}
然后创建一个使用反射来设置属性的通用映射器:
static class GenericMapper<T> where T : new()
{
public static T Map(IEnumerable<GenericCustomer> genericCustomer)
{
var mapType = typeof(T);
T instance = new();
foreach(var property in mapType.GetProperties())
{
var genericValue = genericCustomer.FirstOrDefault(x => property.Name.Equals(x.Property, StringComparison.InvariantCultureIgnoreCase));
if (genericValue != null)
{
property.SetValue(instance, genericValue.ToString());
}
}
return instance;
}
}
然后将其用作:
var customer = GenericMapper<Customer>.Map(getData);
Console.WriteLine(customer.CustomerId);
Console.WriteLine(customer.CustomerName);
Console.WriteLine(customer.CustomerTitle);
Console.WriteLine(customer.CustomerGender);
如果您没有更具体地说明您的类定义,我无法进一步帮助您,但这应该给您一个基线。