将类型传递给方法并返回属性值

时间:2013-11-13 10:20:23

标签: c# generics refactoring

我正在尝试从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; }
}

感谢您的帮助。

3 个答案:

答案 0 :(得分: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" ));

答案 1 :(得分: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";
    }

}

然后在Main:

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

答案 2 :(得分: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 );

但是这真的给你买了什么吗?看起来你只会将复杂性添加到完全可读的东西中。