加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 17:38:24 所属栏目:百科 来源:网络整理
导读:我有一个ComboBox,其中填充使用匿名类型的集合: var results = (from row in data.Tables[0].AsEnumerable() select new { Id = row.Fieldint("id"),Name = row.Fieldstring("Name }).Distinct();myComboBox.ValueMember = "Id";myComboBox.DisplayMember =
我有一个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);
}

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

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

            ??? ???
    }  
}

有任何想法吗?

解决方法

你也可以使用反射.
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);
    }  
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读