C#中通过反射创建匿名对象
有没有办法在 .NET 3.5 运行时通过反射创建 C# 3.0 匿名对象? 我想在我的序列化方案中支持它们,所以我需要一种以编程方式操作它们的方法。
稍后进行编辑以澄清用例
一个额外的限制是我将在 Silverlight 应用程序中运行所有这些内容,因此额外的运行时不是一个选项,并且不确定动态生成代码将如何工作。
Is there any way to create C# 3.0 anonymous object via Reflection at runtime in .NET 3.5? I'd like to support them in my serialization scheme, so I need a way to manipulate them programmatically.
edited later to clarify the use case
An extra constraint is that I will be running all of it inside a Silverlight app, so extra runtimes are not an option, and not sure how generating code on the fly will work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这是另一种方式,似乎更直接。
Here is another way, seems more direct.
就在这里。
从记忆里:
Yes, there is.
From memory:
使用反射获取Type,对类型使用GetConstructor,对构造函数使用Invoke。
编辑:感谢 Sklivvz 指出我回答了一个没有被问到的问题;)
实际问题的答案:我发现生成 C# 代码,然后使用 CodeDomProvider(但不是 CodeDOM 本身 - 可怕),然后编译它并从中反映类型是在运行时处理“匿名”对象的最简单方法。
Use reflection to get the Type, use GetConstructor on the type, use Invoke on the constructor.
Edit: Thanks to Sklivvz for pointing out that I answered a question that wasn't asked ;)
The answer to the actual question: I've found that generating C# code and then using CodeDomProvider (but not CodeDOM itself -- terrible) and then compiling that down and reflecting types out of that is the easiest way of doing 'anonymous' objects at runtime.
您可能想调查一下 DLR。 我自己还没有这样做,但 DLR(动态语言)的用例听起来很像您想要做的事情。
根据您想要执行的操作,Castle 框架的动态代理对象可能也很合适。
You might want to look into the DLR. I havn't done so myself (yet) but the use-case for the DLR (dynamic languages) sounds a lot like what you're trying to do.
Depending on what you want to do the Castle-framework's dynamic proxy object might be a good fit too.
您可以使用 Reflection.Emit 动态生成所需的类,尽管编写代码非常麻烦。
如果您决定采用此路线,我建议您下载 Reflection Emit Language Addin for .NET Reflector,因为这允许您查看如何使用 Reflection.Emit 构建现有类,因此学习框架这一角的好方法。
You can use Reflection.Emit to generate the required classes dynamically, although it's pretty nasty to code up.
If you decide upon this route, I would suggest downloading the Reflection Emit Language Addin for .NET Reflector, as this allows you to see how existing classes would be built using Reflection.Emit, hence a good method for learning this corner of the framework.
您可能还想查看 FormatterServices 类: FormatterServices 上的 MSDN 条目
它包含 GetSafeUninitializedObject,它将创建该类的空实例,以及在进行序列化时的其他几个方便的方法。
回复迈克尔的评论:
如果您没有类型 T 的 Type 实例,则始终可以从 typeof(T) 获取它。 如果您有一个未知类型的对象,您可以对其调用 GetType() 以获取 Type 实例。
You might also want to have a look into the FormatterServices class: MSDN entry on FormatterServices
It contains GetSafeUninitializedObject that will create an empty instance of the class, and several other handy methods when doing serialization.
In reply to comment from Michael:
If you don't have the Type instance for type T, you can always get it from typeof(T). If you have an object of an unknown type, you can invoke GetType() on it in order to get the Type instance.