如何在运行时动态向 ExpandoObject 添加属性?

问题描述 投票:0回答:1

下面是我想要做的代码片段。

dynamic model = new ExpandoObject();

foreach (Control control in ConfigData.ActiveForm.Controls)
{
    string controlType = control.GetType().ToString();
    if (controlType == "System.Windows.Forms.TextBox")
    {
        TextBox txtBox = (TextBox)control;
        if (string.IsNullOrEmpty(txtBox.Text))
        {
            MessageBox.Show(txtBox.Name + " Can not be empty");
            return;
        }
        model[txtBox.Name] = txtBox.Text; // this gives error
    }
}

我想创建一个属性,其值的名称来自

txtBox.name

例如,如果

textBox.name
的值为
"mobileNo"
,我想向
mobileNo
添加一个名为
model
的属性。我该怎么做?

c# asp.net .net expandoobject
1个回答
2
投票
dynamic expando = new ExpandoObject();

// Add properties dynamically to expando
AddProperty(expando, "Language", "English");

public static void AddProperty(ExpandoObject expando, string propertyName, object propertyValue)
{
    // ExpandoObject supports IDictionary so we can extend it like this
    var expandoDict = expando as IDictionary<string, object>;
    if (expandoDict.ContainsKey(propertyName))
        expandoDict[propertyName] = propertyValue;
    else
        expandoDict.Add(propertyName, propertyValue);
}

感谢 Jay Hilyard 和 Stephen Teilhet

来源:https://www.oreilly.com/content/building-c-objects-dynamically/

© www.soinside.com 2019 - 2024. All rights reserved.