[英]How to check multiple properties on an object have the same condition?
我有一個相當長且笨拙的方法,該方法將對象作為參數,然后根據相同的條件(==“隨機”)檢查每個屬性,並對屬性執行特定的操作。
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....
是否有可能以某種方式對照同一條件檢查我的所有屬性,然后減少我的代碼,使對單個屬性的所有操作都在同一代碼塊內? 因此,一個代碼塊是= random,另一個是。
非常感謝,
我通常更喜歡為此目的使用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");
}
接着:
if (CheckAllProperties(user))
{
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.