1

从 API 读取数据时,我试图减少代码。我有很多非常相似的方法,我确信我可以将它们重构为一种,我只需要指出正确的方向。下面是一个非常简化的代码版本 -

我想将“ReturnManagerName”和“ReturnTrainerName”重构为一种方法,有人可以帮忙吗?

void Main()
{
  Team team = new Team();

  Manager manager = new Manager();
  manager.ManagerName = "Mr Manager";

  team.TeamManager = manager;

  Console.WriteLine ("Manager: " + ReturnManagerName(team));
  Console.WriteLine ("Trainer: " + ReturnTrainerName(team));
}

string ReturnManagerName(Team team)
{
  if(team.TeamManager == null)
    return "None";
  return team.TeamManager.ManagerName;
}

string ReturnTrainerName(Team team)
{
  if(team.TeamTrainer == null)
    return "None";
  return team.TeamTrainer.TrainerName;
}

public class Team
{
  public Manager TeamManager { get; set; }
  public Trainer TeamTrainer { get; set; }
}

public class Manager
{
  public string ManagerName { get; set; }
}

public class Trainer
{
  public string TrainerName { get; set; }
}

谢谢你的帮助。

4

3 回答 3

1

根据评论更新:

public class Person 
{
    public Person(string name)
    {
        Name = name;
    }

    public string Name { get; set; }
}


public class Team
{
    public Person Manager { get; set; }
    public Person Trainer { get; set; }
}

public class PrettyPrinter
{
    public string GetNameOrNone(Person p)
    {
        return p != null ? p.Name : "None";
    }

}

然后在主要:

{
    Team team = new Team();

    team.Manager = new Person("Mr. Manager");

    PrettyPrinter p = new PrettyPrinter();

    Console.WriteLine ("Manager: " + p.GetNameOrNone(team.Manager));
    Console.WriteLine ("Trainer: " + p.GetNameOrNone(team.Trainer));
}
于 2013-11-13T10:38:00.923 回答
1

你可以使用反射来做到这一点。

string ReturnTeamMemberName(object manager, string propName)
{
   if(manager == null)
      return "None";      
   return manager.GetType().GetProperty(propName).GetValue(manager, null).ToString();
}

称它为,

Console.WriteLine ("Manager: " + ReturnTeamMemberName(team.TeamManager, "ManagerName"));
Console.WriteLine ("Trainer: " + ReturnTeamMemberName(team.TeamTrainer,"TrainerName" ));
于 2013-11-13T10:27:21.830 回答
0

可以这样做:

Tuple<string,string> ReturnNames(Team team)
{
  var trainerName = (team.TeamTrainer == null)? "None" : team.TeamTrainer.TrainerName;
  var managerName = (team.TeamTrainer == null)? "None" : team.TeamManager.ManagerName;
  return Tuple.Create(trainerName, managerName);
}

var tuple = ReturnNames(team);
Console.WriteLine ("Manager: " + tuple.Item1 );
Console.WriteLine ("Trainer: " + tuple.Item2 );

但这真的能给你带来什么吗?看起来你只会增加一些完全可读的东西的复杂性。

于 2013-11-13T10:26:21.593 回答