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

时间:2017-02-28 19:19:17

标签: c# object properties conditional-statements

我有一个非常长而且笨拙的方法,它接受一个对象作为参数,然后根据相同的标准(==“random”)检查每个属性,并对该属性执行特定的操作。

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 = random而另一个是for else。

非常感谢,

1 个答案:

答案 0 :(得分:4)

我更喜欢通常使用LINQ:

public class calculator extends JPanel{
public static final int WIDTH=320;
public static final int HEIGHT=480;
private GridBagLayout layout;
private GridBagConstraints gbc;
private JButton[] newbuttons;
private JTextField text;
private int[][] newConstraints= new int[][]{
        {0,5,2,1},
        {0,4,1,1},
        {1,4,1,1},
        {2,4,1,1},
        {0,0,1,1},
        {0,0,1,1},
        {0,0,1,1},
        {0,0,1,1},
        {0,0,1,1},
};
public calculator(){
    setPreferredSize(new Dimension(WIDTH,HEIGHT));
    layout=new GridBagLayout();
    layout.columnWidths= new int[]{110,120,40,80};
    layout.rowHeights= new int[]{80,80,80,80,80,80};
    setLayout(layout);
    gbc= new GridBagConstraints();
    newbuttons=new JButton[10];
    for(int i=0;i<newbuttons.length;i++){
        newbuttons[i]=new JButton(""+i);
        gbc.gridx=newConstraints[i][0];
        gbc.gridy=newConstraints[i][1];
        gbc.gridwidth=newConstraints[i][2];
        gbc.gridheight=newConstraints[i][3];
        gbc.fill=GridBagConstraints.BOTH;
        add(newbuttons[i],gbc);
    }


}
    public static void main(String[] args) {
        JFrame frame= new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());
        frame.add(new calculator(), BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);
    }

}

然后:

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");
}