下面是我想要做的代码片段。
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
的属性。我该怎么做?
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/