[英]How to check multiple properties on an object have the same condition?
I have a pretty long and unwieldy method which takes in an object as a parameter, then checks every property against the same criteria (== "random") and performs a specific action against the property. 我有一个相当长且笨拙的方法,该方法将对象作为参数,然后根据相同的条件(==“随机”)检查每个属性,并对属性执行特定的操作。
public void CreateRegistration(UserGroup user, int mobileLength, int passwordLength, int questionLength) {
if (user.Title == "random") {
title.ClickDropdown();
} else {
WebElementExtensions.ClickDropdown(title,user.Title);
}
if (user.Firstname == "random") {
firstName.SendKeys(GenerateData.GenerateRandomName());
} else {
firstName.SendKeys(user.Firstname);
}
if (user.Middlename == "random") {
middleName.SendKeys(GenerateData.GenerateRandomName());
} else {
firstName.SendKeys(user.Middlename);
}
etc....
Is it possible to somehow check all my properties against the same criteria together, then reduce my code so all the actions on the individual properties are within the same code block? 是否有可能以某种方式对照同一条件检查我的所有属性,然后减少我的代码,使对单个属性的所有操作都在同一代码块内? so one code block for is = random and one for else.
因此,一个代码块是= random,另一个是。
Many thanks, 非常感谢,
I prefer to use LINQ for this purpose usually: 我通常更喜欢为此目的使用LINQ:
private bool CheckAllProperties(UserGroup instance)
{
return instance.GetType().GetProperties()
.Where(c => c.GetValue(instance) is string)
.Select(c => (string)c.GetValue(instance))
.All(c => c== "random");
}
And then: 接着:
if (CheckAllProperties(user))
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.