简体   繁体   English

如何检查一个对象的多个属性具有相同的条件?

[英]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.

相关问题 检查实体是否具有相同的属性 - Check if the entities have same properties EFCore - 如何将多个导航属性设置为相同类型? - EFCore - How to have multiple navigation properties to the same type? 如何使用反射来调节多个属性以检查 LINQ .Where 语句中的相等性,具体取决于传递的类? - How use Reflection to condition multiple properties to check for equality in a LINQ .Where statement, depending on what class is passed? 如何在具有两个属性的对象列表中检查具有相同属性的所有对象是否也具有相同的其他属性? - How to check if in a list of Objects with two properties, all Objects with one equal property also have the same other property? LINQ - 从同一 object 中的多个属性中选择许多 - LINQ - SelectMany from multiple properties in same object 比较几个对象并检查是否具有相同的值 - Compare few object and check are have same value 使用 Fluent Validation 如何检查对象中的两个属性都不能有值? - Using Fluent Validation how can I check that two properties in an object both can't have a value? 如何缓存具有多个属性的对象 - How to cache an object with multiple properties 如何告诉Automapper检查所有源属性是否都具有目标属性 - How to tell Automapper to check if all source properties have destination properties 如何检查是否存在相同的 Random 对象 - How to check there is the same Random object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM