gpt4 book ai didi

c# - 将具有键值属性的对象 [] 映射到对象的属性,而无需使用巨大的讨厌开关

转载 作者:行者123 更新时间:2023-11-30 15:20:37 24 4
gpt4 key购买 nike

我有一个键值对象数组。

public class KeyValueStore
{
public string Key {get;set;}
public string Value {get;set;}
}

这个数组存储我试图像这样填充的对象的值:

public class Customer
{
public string Name {get;set;}
public string Country {get;set}
}

所以我想将这些键从 KeyValueStore 映射到客户属性

public Customer TransformToCustomer(KeyValueStore[] keyValueStore)
{
var customer = new Customer();

foreach (var keyValue in keyValueStore)
{
switch (keyValue.Key)
{
case "Name":
customer.Name = keyValue.Value;
break;
case "Cntry":
customer.Country = keyValue.Value;
break;
}
}

return customer;
}

有更好的方法吗?

最佳答案

是的,假设目标类型有一个无参数的构造函数,您可以编写一个泛型方法来执行此操作:

public T CreateAndPopulate<T>(IEnumerable<KeyValueStore> propStore,
IDictionary<string, string> mapping = null)
where T:class,new()
{

T item=new T();
var type=typeof(T);
foreach(var kvs in propStore)
{
var propName = kvs.Key;
propName = mapping !=null && mapping.ContainsKey(propName)
? mapping[propName]
: propName;
var prop = type.GetProperty(propName);
if(prop == null) //does the property exist?
{
continue;
}
var propMethodInfo = prop.GetSetMethod();
if(propMethodInfo == null) //does it have a set method?
{
continue;
}
propMethodInfo.Invoke(item, new[]{ kvs.Value });
}
return item;
}

并使用它:

IEnumerable<KeyValueStore> propStore = new KeyValueStore[]{
new KeyValueStore{ Key = "Name", Value = "John" },
new KeyValueStore{ Key = "Cntry", Value = "UK" }};
var mapping = new Dictionary<string,string>{{ "Cntry", "Country" }};

var customer = CreateAndPopulate<Customer>(propStore, mapping);

关于c# - 将具有键值属性的对象 [] 映射到对象的属性,而无需使用巨大的讨厌开关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39773870/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com