动态设定一个C#匿名类型的属性名称 [英] Dynamically set the property name of a C# anonymous type

查看:1240
本文介绍了动态设定一个C#匿名类型的属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么办法来动态地设置一个匿名类型的属性名称

Is there any way to dynamically set the property name of an anonymous type?

通常我们会做这样的:

var anon = new { name = "Kayes" };

现在我想动态设置属性的名称(或标识),使这一名称可能来自一个XML文件或数据库中。

Now I'd like to set the name (or identifier) of the property dynamically, so that this name can come from an XML file or a database.

谢谢你们为你的答案。不,我需要的是绝对不值得所有繁琐的替代品。我只是想让我的代码遵守,是由我的团队负责开发现有的库。但是,我们决定更新库,支持字典类型,以便它可以很容易解决的。

Thanks guys for your answers. No, my need is definitely not worth all the tedious alternatives. I just wanted to make my code comply with an existing library that was developed by my team lead. But we decided to update the library to support Dictionary types so that it can easily be solved.

皮特,我真的很兴奋,以了解动态类型在.NET 4.0中

Pete, I'm really excited to learn about dynamic types in .NET 4.0

感谢。

推荐答案

这是不可能的,因为即使类型是匿名的,它不是一个动态类型。它仍然是一个静态类型,并且它的属性必须在编译时是已知的。

That is not possible because even though the type is anonymous, it is not a dynamic type. It is still a static type, and properties about it must be known at compile time.

您可能要检查出.NET 4.0动态的关键字生成真正的动态类。

You might want to check out the .NET 4.0 "dynamic" keyword for generating true dynamic classes.

这篇关于动态设定一个C#匿名类型的属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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