从匿名对象获取值

本文关键字:获取 对象 | 更新日期: 2023-09-27 18:01:07

我在DataGrid中有一个匿名类型列表,我需要获得第一个值(EmployeeId(,这是一个整数。

当我编译应用程序时,我可以看到变量(selectedEmployee(中的值。

像这样:

selectedEmployee = 
{
    EmployeeId = 402350236,
    OperatorNum = 12,
    StateName = "Active",
    Name = "Robert",
    LastName = "Tedd Zelaya",
    Password = "abcd",
    DateBegin = {13/07/2011 0:00:00},
    DateEnd = {23/07/2011 0:00:00},
    Telephone = "8869-2108",
    Address = "Santa Barvara"
    ... 
}

这是当用户clic在网格中的项目上时我的代码。

var selectedEmployee = _employeedataGrid.CurrentCell.Item;

我也尝试了这个:

DataRowView dataRowView = _employeedataGrid.CurrentCell.Item as DataRowView;
            var idEmployee = 0;
            if (dataRowView != null) 
            {
                idEmployee = Convert.ToInt32(dataRowView.Row[0]);
            }

但是dataRowView始终为Null。不工作。。。

如何从该对象中获取第一个值?

从匿名对象获取值

网格中的项目不是DataRowView的,它们是匿名的。您必须使用反射,或者使用dynamic

dynamic currentItem = _employeedataGrid.CurrentCell.Item;
int idEmployee = currentItem.EmployeeId;

另一方面,如果使用强类型对象会更好。为其创建类或使用Tuple(或其他(。

DataRowView为null,因为CurrentCell.Item是一个匿名类型的对象,而不是DataRowView。as运算符将LHS强制转换为RHS上指定的类型,如果无法将项强制转换为RH,则返回null。

由于CurrentCell.Item是匿名类型,因此不能强制转换它来检索EmployeeId。我建议创建一个具有所需属性的类(称之为Employee类(,并将数据网格绑定到这些Employees的集合。然后你可以说

var selectedEmployee = (Employee)_employeedataGrid.CurrentCell.Item;
int? selectedId = selectedEmployee == null? (int?)null : selectedEmployee.EmployeeId;