我正在探索在.NET 4.0中的DynamicObject模型。该应用程序是其中一个目的将通过某种文本/ xml文件来描述,并且该程序必须在阅读该文件创建对象
I am exploring the DynamicObject model in .NET 4.0. The application is one where an object will be described through some sort of text/xml file, and the program must create an object upon reading that file.
通过DynamicObject,我们可以轻松地添加成员,因为我们知道该成员的先验的名称。但是,如果我们甚至不知道添加的成员的名字?有没有一种方法,使这种动态呢?
With DynamicObject, we can add members easily, given that we know the name of the member a priori. But, what if we don't even know the name of the member to add? Is there a way to make that dynamic as well?
举例来说,说我需要与成员Property1','Property2创建一个对象,并用PropertyA另一个对象,并且所描述的文本/ XML文件'PropertyB。如何动态创建一个对象,在此基础上的信息?
For example, say I need to create an object with members 'Property1', 'Property2', and another object with 'PropertyA', and 'PropertyB' as described by the text/XML file. How can I create an object dynamically based on this info?
更新 我有一些想法,从这篇文章:http://www.$c$cproject.com/KB/cs/dynamicincsharp.aspx
UPDATE I got some ideas from this post: http://www.codeproject.com/KB/cs/dynamicincsharp.aspx
该实现允许我做类似如下:
This implementation allows me to do something like the following:
dynamic d = new PFDynamicChannel();
PFCouplings c = ((PFChannel)d).Coupling;
d.NewProperty = "X";
我不希望使用字典的原因是利用TryGetMember,并TrySetMember方法,我可以重写,在其中我可以提高,这对于该方案必不可少的活动。
The reason I do not wish to use a dictionary is to make use of TryGetMember, and TrySetMember methods that I can override, within which I can raise events that are essential for the program.
这样的话,我可以从一个基类(PFChannel)继承,但我也可以在飞行中添加成员。不过,我的问题是,我不知道这个新属性的名字,直到运行时。而且,实际上我不认为动态对象可以让我在飞行中增加新的特性。如果是这样的话,我怎么能利用ExpandoObject的给我这个能力吗?
This way, I can inherit from a base class (PFChannel), but I can also add members on the fly. But, my problem is that I will not know the new property name until runtime. And, I actually don't think the dynamic object allows me to add new properties on the fly. If this is the case, how can I make use of ExpandoObject to give me this ability?
推荐答案
如果您的只有的需要做的是,你应该看看ExpandoObject.如果你需要做的的和的仍使用 DynamicObject
,你将需要写code记的属性值,基本上...这你可能用做嵌入式 ExpandoObject
。
If you only need to do that, you should look at ExpandoObject
. If you need to do that and still use DynamicObject
, you will need to write code to remember property values, basically... which you could potentially do with an embedded ExpandoObject
.
这我不清楚你想要做与此对象之后,虽然什么 - 你确定你需要动态类型呢?将一个词典<字符串,对象>
实际上是更糟?这要看是怎么回事消费对象后基本相符。
It's not clear to me what you want to do with this object afterwards though - are you sure you need dynamic typing at all? Would a Dictionary<string, object>
actually be any worse? It depends what's going to consume the object later basically.
相关推荐
最新文章