从字典中的属性C#匿名对象 [英] C# anonymous object with properties from dictionary

查看:1674
本文介绍了从字典中的属性C#匿名对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个字典转换为匿名类型与一个属性为每个关键。

I'm trying to convert an dictionary to an anonymous type with one property for every Key.

我试图谷歌,但所有我能找到的是如何转换一个匿名对象字典。

I tried google it but all I could find was how to convert a anonymous object to a dictionary.

我的字典看起来是这样的:

My dictionary looks something like this:

var dict = new Dictionary<string, string>
{
    {"Id", "1"},
    {"Title", "My title"},
    {"Description", "Blah blah blah"},
};



,我想返回一个匿名对象,看起来像这样。

And i would like to return a anonymous object that looks like this.

var o = new 
{
    Id = "1",
    Title = "My title",
    Description = "Blah blah blah"
};



所以,我会把它想环通每keyValuePair在字典中,并在对象创建一个属性每一个键。

So I would like it to loop thru every keyValuePair in the dictionary and create a property in the object for every key.

我不知道从哪里开始。

请帮忙。

推荐答案

您不能,基本上是这样。匿名类型是由编译器创建的,所以他们在汇编中存在与烤到他们所有的财产的名称。 (该属性的类型的是在此情况下的一个问题 - 作为一个实现细节,编译器创建的通用型,然后创建的,使用适当类型的参数的实例。)

You can't, basically. Anonymous types are created by the compiler, so they exist in your assembly with all the property names baked into them. (The property types aren't a problem in this case - as an implementation detail, the compiler creates a generic type and then creates an instance of that using appropriate type arguments.)

您正在寻求一种与以的执行的决定性质的时间 - 这只是不具有匿名类型是如何工作的契合。你不得不基本上编译使用它在执行时的代码 - 那么这将是一个痛苦,因为它会在不同的装配和匿名类型是内部...

You're asking for a type with properties which are determined at execution time - which just doesn't fit with how anonymous types work. You'd have to basically compile code using it at execution time - which would then be a pain as it would be in a different assembly, and anonymous types are internal...

也许你应该使用 ExpandoObject 呢?然后,使用动态什么就能访问属性为正常。

Perhaps you should use ExpandoObject instead? Then anything using dynamic will be able to access the properties as normal.

这篇关于从字典中的属性C#匿名对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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