从其他方法访问C#匿名类型

Gab*_*iel 9 c# linq anonymous-types

我有一个使用匿名类型集合填充的ComboBox:

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);
}
Run Code Online (Sandbox Code Playgroud)

然后,在comboBox的SelectedIndexChanged方法中,我想检索所选项的Id,但我无法访问"Id"属性,在myComboBox中.SelectedItem是所选对象.

private void myComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    if (myComboBox.SelectedItem != null)
    {
        var x = myComboBox.SelectedItem;

            ¿¿¿ ???
    }  
}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Jon*_*s B 9

由于您使用Id作为值成员,因此Id将存储为myComboBox.SelectedItem.Value


Agu*_*les 4

您也可以使用反射。

private void myComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    if (myComboBox.SelectedItem != null)
    {
        var x = myComboBox.SelectedItem;
        System.Type type = x.GetType();
        int id = (int)type.GetProperty("Id").GetValue(obj, null);
    }  
}
Run Code Online (Sandbox Code Playgroud)