在 C# 中动态 select Ienumerable 属性
dynamically select Ienumerable property in c#
我正在尝试执行以下断言
Assert.AreEqual<string>(A.Drivers[i].FirstName, Response);
Drivers 是 IEnumerable 集合,它还有其他属性,如姓氏、中间名等。我想动态 select Drivers 的属性,以便它可以用一种方法完成,而不是为每个 属性
编写不同的方法
你可以使用反射来做到这一点:
获取驱动程序的字符串属性class
var driverProperties = typeof(Drivers).GetProperties().Where(i => i.PropertyType.Equals(typeof(string)));
然后遍历属性
foreach (var property in driverProperties)
{
Assert.AreEqual<string>(property.GetValue(A.Drivers[i]), Response);
}
对 Dano 的建议稍作修改。要获得一个特定的 属性
var prop = typeof(Drivers).GetProperty("propName");
var val = (string)prop.GetValue(A.Drivers[i]);
我正在尝试执行以下断言
Assert.AreEqual<string>(A.Drivers[i].FirstName, Response);
Drivers 是 IEnumerable 集合,它还有其他属性,如姓氏、中间名等。我想动态 select Drivers 的属性,以便它可以用一种方法完成,而不是为每个 属性
编写不同的方法你可以使用反射来做到这一点:
获取驱动程序的字符串属性class
var driverProperties = typeof(Drivers).GetProperties().Where(i => i.PropertyType.Equals(typeof(string)));
然后遍历属性
foreach (var property in driverProperties)
{
Assert.AreEqual<string>(property.GetValue(A.Drivers[i]), Response);
}
对 Dano 的建议稍作修改。要获得一个特定的 属性
var prop = typeof(Drivers).GetProperty("propName");
var val = (string)prop.GetValue(A.Drivers[i]);