如何使用大括号{ID:1,名称:John}访问成员

时间:2018-11-16 02:19:42

标签: c# winforms

我在大括号中为变量“ StudentInfo”分配了以下值:

var StudentId = StudentBll.GetStudents(false).Select(t => new { ID = t.ID, Name = t.Name }).ToList();


            comboStudent.DataSource = StudentId;
            comboStudent.DisplayMember = "Name";
            comboStudent.ValueMember = "ID";

var StudentInfo = comboStudent.SelectedItem;

var StudentInfo的值返回为:

{ ID: 1, Name: "John" }
    ID: 1
    Name: "John"

如何仅从StudentInfo引用名称? 例如, lblName.Text = StudentInfo.Name ? lblName.Text = StudentInfo(0).Name ? 两者都不起作用...

1 个答案:

答案 0 :(得分:1)

ComboBox的SelectedItem属性返回object。只有在运行时,我们才知道它拥有什么价值。这就是为什么不能使用StudentInfo.Name的原因,因为从编译器的角度来看,您正在做类似var StudentInfo = new object(); Console.WriteLine(StudentInfo.Name);的事情:object不包含属性Name

您的下一个问题是您使用的是匿名类型(new { ID = t.ID, Name = t.Name }),因此不能仅将SelectedItem强制转换回该类型。

一些选项是:

1。定义一个班级

public class BasicStudent
{
    public int ID {get;set;}
    public string Name {get;set;}
}

将您的选择更改为.Select(t => new BasicStudent { ID = t.ID, Name = t.Name }),然后再投射.SelectedItemConsole.WriteLine(((BasicStudent)comboStudent.SelectedItem));

2。使用原始课程

停止选择匿名类型,仅按原样使用该对象。然后只需从.SelectedItem回退:Console.WriteLine(((Student)comboStudent.SelectedItem));

3。使用动态

dynamic student = comboStudent.SelectedItem;
Console.WriteLine(student.Name.ToString());

4。使用技巧性的技巧将comboStudent.SelectedItem转换回匿名类型

请参见答案here