gpt4 book ai didi

c# - 如何将常量和类属性值映射到 Dictionary

转载 作者:行者123 更新时间:2023-11-30 17:52:09 25 4
gpt4 key购买 nike

我有一个类叫做 Contact和另一个名为 ContactKeys 的类包含 Int32常数。每个常量映射到 Contact 的一个属性类并具有相同的名称。

public class Contact
{
public string Name { get; set; }
public int Age { get; set; }
}

public static class ContactKeys
{
public const int Name = 5284;
public const int Age = 9637;
}

使用 Automapper,我需要创建一个 Dictionary<int, object>键是 ContactKey 中的常量的对象,并且该值由 Contact 中的同名属性提供类(class)。

来自 this post我可以看到可能会序列化 Contact类到 JSON,然后将其映射。但我不知道如何映射常量。

有什么想法吗?

最佳答案

我不知道 AutoMapper 以及为什么需要使用它来解决这个问题,但这里有一个使用反射的解决方案:

Contact myContact = ...;

typeof(ContactKeys)
.GetFields(BindingFlags.Public | BindingFlags.Static)
.ToDictionary(f => (int)f.GetValue(null),
f => typeof(Contact).GetProperty(f.Name).GetValue(myContact));

关于c# - 如何将常量和类属性值映射到 Dictionary<int, object>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18653618/

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