转换字典<字符串,对象>匿名对象?

转换字典<字符串,对象>匿名对象?

问题描述:

首先,使事情更清楚,我会从上面解释一下我的情况:

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 []是非常简单的。因此,我想创造一个词典这将持有的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$c$c>:

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;

但我不知道怎么做的会帮助你。

But I'm not sure how is doing that going to help you.