转换字典<字符串,对象>匿名对象? [英] Convert Dictionary&lt;string, object&gt; To Anonymous Object?

查看:50
本文介绍了转换字典<字符串,对象>匿名对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,为了让事情更清楚,我将从顶部解释我的场景:

First, and to make things clearer I'll explain my scenario from the top:

我有一个具有以下签名的方法:

I have a method which has the following signature:

public virtual void SendEmail(String from, List<String> recepients, Object model)

我想要做的是生成一个匿名对象,它具有模型对象的属性以及前两个参数.将模型对象展平为 PropertyInfo[] 非常简单.因此,我想到创建一个 Dictionary 来保存 PropertyInfo 和前两个参数,然后将其转换为匿名对象,其中键是属性的名称,值是属性的实际值.

What I want to do is generate an anonymous object which has the properties of the model object along with the first two parameters as well. Flattening the model object into a PropertyInfo[] is very straightforward. Accordingly, I thought of creating a Dictionary which would hold the PropertyInfo's and the first two params, and then be converted into the anonymous object where the key is the name of the property and the value is the actual value of the property.

这可能吗?还有其他建议吗?

Is that possible? Any other suggestions?

推荐答案

如果你真的想把字典转换成一个以字典的项目为属性的对象,你可以使用 ExpandoObject:

If you really want to convert the dictionary to an object that has the items of the dictionary as properties, you can use ExpandoObject:

var dict = new Dictionary<string, object> { { "Property", "foo" } };
var eo = new ExpandoObject();
var eoColl = (ICollection<KeyValuePair<string, object>>)eo;

foreach (var kvp in dict)
{
    eoColl.Add(kvp);
}

dynamic eoDynamic = eo;

string value = eoDynamic.Property;

这篇关于转换字典<字符串,对象>匿名对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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