添加未知的(在设计时)属性的ExpandoObject [英] Adding unknown (at design time) properties to an ExpandoObject

查看:192
本文介绍了添加未知的(在设计时)属性的ExpandoObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是探索C#4,试图让我的头周围的一切这个充满活力的东西。很抱歉,如果这个问题是愚蠢的,在这个领域没有经验。

just exploring c# 4. Trying to get my head around all this dynamic stuff. Sorry if this question is silly, no experience in this domain.

如果我有一个ExpandoObject,并希望在运行时添加公共属性(使用get和set)它,我将如何去这样做?

If I have an ExpandoObject and want to add public properties (with get and set) to it at runtime, how would I go about doing it?

例如,我有一个documentTemplate和文件,其中有对documentTemplate指着一个属性。这documentTemplate已经得到了一些双打冠军(学生开发的如:功能),应同时使(如注意力,记忆力等)的文件来解决。所以,只要模板文件中设置,我想创建一个类,它具有相同的名称作为模板的双打冠军,然后使用一些UI元素,如PropertyGrid的特性,我可以让用户填写标签值对双打冠军。

For example, I have a documentTemplate and a document, which has a property pointing towards the documentTemplate. This documentTemplate has got some tag Titles (eg. Capabilities developed among students), which should be addressed while making the document (eg. Concentration, memory etc.). So as soon as the template is set in the document, I want to create a class, which has properties with same names as the tag titles in the Template, and then using some UI element, such as the PropertyGrid, I can have the user fill in tag values against the tag Titles.

感谢您阅读!

推荐答案

我不知道怎么有可能将成员添加到飞一类,并与此示例想出了:

I wondered how it might be possible to add members to a class "on the fly" and came up with this sample:

using System;
using System.Collections.Generic;
using System.Dynamic;

class Program
{
    static void Main()
    {
        dynamic expando = new ExpandoObject();
        var p = expando as IDictionary<String, object>;

        p["A"] = "New val 1";
        p["B"] = "New val 2";

        Console.WriteLine(expando.A);
        Console.WriteLine(expando.B);
    }
}

这code代码片段的一点是,成员A和B被定义为字符串(硬codeD /字符串化),并通过ExpandoObject的IDictionary的接口增加。我们对键的存在和值来测试(并证明这一概念)通过直接访问他们,并输出到控制台。

The point of this code snippet is that the members A and B are defined as string literals (hard coded/stringified) in and added via ExpandoObject's IDictionary interface. We test for the keys' existence and values (and prove the concept) by accessing them directly and outputting to console.

这篇关于添加未知的(在设计时)属性的ExpandoObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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