传递参数的清洁方式

时间:2014-02-19 05:13:13

标签: c#

public EmployeeProcessOutput RetrieveEmployee(EmployeeProcessInput input)
{     
      var employee = input.Employee;
      if (input.EmployeeId == null)
          employee= CreateEmployee(employee);

      return new EmployeeProcessOutput
            {
                Employee = employee,
                State = "Stored" 
            };
}

private Employee CreateEmployee(employee)
{
      //Call a service to create an employee in the system using the employee 
      //info such as name, address etc and will generate an id and other 
      //employee info.
      var output = Service(employee)
      var employee = output.Employee;
      return employee;
 }

是否有一种干净的方式并将employee参数传递给CreateEmployee方法。我觉得这条线可以更清洁:

employee = CreateEmployee(employee);

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

您是在谈论通过引用传递而不是返回并分配Employee值?如果是这样,你可以这样做:

public EmployeeProcessOutput RetrieveEmployee(EmployeeProcessInput input)
{     
      var employee = input.Employee;
      if (input.EmployeeId == null)
          CreateEmployee(ref employee);

      return new EmployeeProcessOutput
            {
                Employee = employee,
                State = "Stored" 
            };
}

private void CreateEmployee(ref Employee employee)
{
      //Call a service to create an employee in the system using the employee 
      //info such as name, address etc and will generate an id and other 
      //employee info.
      var output = Service(employee)
      employee = output.Employee;
 }

请注意,您必须使用ref关键字,因为您正在更改参数本身的值。有关详细信息,请参阅this answer

话虽如此,这并不一定会使代码“更清晰”,而且很难确切地说出你在问什么。但出于某种原因,我得到的印象就是你所指的。

答案 1 :(得分:0)

我不会说你已经在做什么有什么问题,但是如果你绝对想改变和简化这一行,也许你可以使用extension method?:

employee = employee.Create();

哪个会打电话:

public static Employee Create(this employee)
{
    // ..call service, etc..

    return employee;
}

请注意,此Create()方法需要驻留在单独的公共静态类中。