如何将常量和类属性值映射到Dictionary< int,object&gt ;? [英] How can I map constants and class property values to a Dictionary<int, object>?

查看:53
本文介绍了如何将常量和类属性值映射到Dictionary< int,object&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 Contact 的类和另一个名为 ContactKeys 的类,其中包含 Int32 常量.每个常量都映射到 Contact 类的属性,并且具有相同的名称.

I have an class called Contact and another class called ContactKeys that contain Int32 constants. Each constant maps to a property of the Contact class and has an identical name.

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 类中的相同名称.

Using Automapper, I need to create a Dictionary<int, object> object where the key is a constant from ContactKey, and the value is provided by the property of the same name from the Contact class.

这篇文章中,我可以看到可能会将 Contact 类序列化为JSON,然后将其映射.但是我不知道该如何映射常量.

From this post I can see that could potentially serialize the Contact class to JSON and then map it. But I don't know how to then get the constants mapped.

有什么想法吗?

推荐答案

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

I don't know AutoMapper and why you need to use it to solve this problem but here is a solution using reflection:

Contact myContact = ...;

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

这篇关于如何将常量和类属性值映射到Dictionary&lt; int,object&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆