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

查看:15
本文介绍了将未知(在设计时)属性添加到 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 的属性.这个文档模板有一些标签标题(例如学生培养的能力),应该在制作文档时解决(例如注意力,记忆力等).因此,一旦在文档中设置模板,我想创建一个类,该类具有与模板中的标签标题同名的属性,然后使用一些 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);
    }
}

此代码片段的要点是成员 A 和 B 被定义为字符串文字(硬编码/字符串化)并通过 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天全站免登陆