C#匿名类型的访问,我在那里用匿名类型的集合填充组合框:其他方法
var results = (from row in data.Tables[0].AsEnumerable()
select new {
Id = row.Field<int>("id"),
Name = row.Field<string>("Name
}).Distinct();
myComboBox.ValueMember = "Id";
myComboBox.DisplayMember = "Name";
foreach (var n in results)
{
myComboBox.Items.Add(n);
}
然后,在下拉列表中的SelectedIndexChanged方法,我想检索所选的Id项,但我无法访问“Id”属性,在myComboBox.SelectedItem中是选定的对象。
private void myComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (myComboBox.SelectedItem != null)
{
var x = myComboBox.SelectedItem;
¿¿¿ ???
}
}
任何想法?
如果你只是需要的ID你可以使用myCombobox.SelectedValue? – saus
* dynamic *关键字会让你陷入困境。匿名类型的成员具有*内部*可访问性。换句话说,当您的UI代码位于单独的程序集中时,您无法访问它们。这是非常普遍的,将UI与数据模型分离是一种值得追求的方式。这里不要使用匿名类型。 –
使用匿名和/或动态类型不是这里的答案。你自己的轻量级类型有什么问题? (或者,对于此特定示例,['KeyValuePair'](http://msdn.microsoft.com/en-us/library/5tbh8a42.aspx)?) –
LukeH