我如何自动映射到的NameValueCollection一个强类型的类? [英] How do I automap namevaluecollection to a strongly typed class?

查看:126
本文介绍了我如何自动映射到的NameValueCollection一个强类型的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的应用程序的详细配置信息存储在一个表像下面:

I have the configuration details of my application stored in a table like below :

SettingName                   SettingValue
--------------------          ---------------------
PostsPerPage                  10   
EmailErrors                   True
AdminEmailAddress             admin@admin.com

我的数据访问类说回报的的NameValueCollection / keyvaluepair存储在表中设置。

My dataaccess class say returns a namevaluecollection / keyvaluepair of settings stored in the table.

会是什么来映射的NameValueCollection / keyvaluepair像下面所述一个强类型类最佳方式具有属性命名一样SettingName柱。

What would be best way to map the namevaluecollection /keyvaluepair to a strongly typed class like the one below that has the properties named the same as in SettingName Column.

public class Settings
{
    public int PostsPerPage{get;set;}
    public bool EmailErrors{get;set;}
    public string AdminEmailAddress{get;set;}
}


推荐答案

使用反射。在伪代码:

Settings mySettingsClass = new Settings();
foreach (KeyValuePair<string, object> kvp in mySettings) 
{
    PropertyInfo pi = mySettingsClass.GetType().GetProperty(kvp.key, BindingFlags.Public | BindingFlags.Instance);
    if (pi != null) 
    {
        pi.SetValue(mySettingsClass, kvp.Value, null);
    }
}



当然,如果你读它背出来的一个DataReader,那么你可以采取稍微不同的方式,避免使用反射(因为DataReader的和目标对象的结构的结构都知道)。在这种情况下使用反射较慢,但是从一个项目到另一个一般的地图数据的好方法 - 基本上你把源属性,看看是否在目标对象上存在目标属性,然后分配值,如果它。

Of course, if you are reading it back out of a dataReader, then you can take a slightly different approach and avoid using reflection (because the structure of the DataReader and the structure of the target object are known). Using reflection in this case is slower, but is a good way to generically map data from one item to another - basically you take the source property, see if the target property exists on the target object, and then assign the value if it does.

这篇关于我如何自动映射到的NameValueCollection一个强类型的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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