如何在运行时动态地向类添加属性? [英] How to add properties to a class Dynamically at run time?

查看:90
本文介绍了如何在运行时动态地向类添加属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在运行时向运行时添加属性。

因为我想要一些客户的电子邮件ID或电话号码。但不是全部,或者我想动态添加一些属性。请建议。

I am trying to add properties to a class at run time that is on the fly.
As in i want some customers email-id or phone no. but not all,or i want to add some properties on the fly.Please suggest .

推荐答案

将能够使用.NET在运行时向类或类的实例添加新属性;您可以在运行时使用Reflection.Emit及其TypeBuilder工具来创建 new 类,并使其从现有Class继承,然后将Properties添加到新类:[ ^ ]。



请注意,如果你进入这个编程领域:它非常复杂,可能会增加你的开发工作的成本。我强烈建议您仔细评估是否真的需要实现此功能。



您可以调查其他替代方案,其中最相关的是:



1.在动态语言运行时(DLR)中使用.NET的Expando对象(FrameWork 4.0):[ ^ ],[< a href =http://www.codeproject.com/Articles/42997/NET-4-0-FAQ-Part-1-The-DLR#What是expando对象target =_ blanktitle =新窗口 > ^ ]。 Anoop Madhusudanan有一篇关于CP的优秀文章:[ ^ ]用DLR编程,使用Expando和DynamicObject,以及他自己非常有趣的弹性对象。



另外检查-out:



2.代码编织,AOP,面向方面编程,其中代码中的结构化注释被呈现为由编译后处理器插入的代码IL:[ ^ ],[ ^ ],[ ^ ]。
You are not going to be able to add new Properties to a Class, or an instance of the Class, at run-time with .NET; you can use Reflection.Emit and its TypeBuilder facility at run-time to create a new Class, and make it inherit from an existing Class, and then add Properties to the new Class: [^].

Please take note that if you go into this area of programming: it is very complex, and may add substantial costs to your development efforts. I strongly advise you carefully evaluate if you really need to implement this feature.

There are other alternatives you might investigate, the most relevant of which is:

1. Use of .NET's Expando object (FrameWork 4.0) in the Dynamic Language Runtime (DLR): [^], [^]. Anoop Madhusudanan has an outstanding article on CP: [^] on programming with DLR, using Expando and DynamicObject, and his own very interesting "Elastic Object.

Also check-out:

2. Code-Weaving, AOP, Aspect Oriented Programming, in which structured comments in your code are rendered into code inserted by a compile post-processor into IL: [^], [^], [^].


这篇关于如何在运行时动态地向类添加属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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