在C#中结合两个方法

时间:2015-01-19 12:10:24

标签: c# methods

所以我有以下两种方法,我想我有什么方法可以将代码减少到一种方法并且优化代码

if语句

外,两种方法几乎相同
private void RepeatSearch()
{
  string optionRead = string.Empty;
  do
  {
   Console.WriteLine("\nPress \"Y\" to Continue ,\"M\" For Main Menu\n");
   Console.Write("Your Choice : ");
  optionRead = Console.ReadLine().ToLower();
   if (optionRead == "y")
    {
     SearchData();
    }
    if (optionRead == "m")
     {
       m.SelectOption();
     }
   else
     {
      Console.ForegroundColor = ConsoleColor.Red;
      Console.WriteLine("\nInvalid Option.Enter M or Y\n");
      Console.ResetColor();
     }
  } while (optionRead != "m" || optionRead != "y");
}

private void RepeatAdd()
{
  string optionRead = string.Empty;
  do
  {
   Console.WriteLine("\nPress \"Y\" to Continue ,\"M\" For Main Menu\n");
   Console.Write("Your Choice : ");
  optionRead = Console.ReadLine().ToLower();
   if (optionRead == "y")
    {
      AddData();
    }
    if (optionRead == "m")
     {
       m.SelectOption();
     }
   else
     {
      Console.ForegroundColor = ConsoleColor.Red;
      Console.WriteLine("\nInvalid Option.Enter M or Y\n");
      Console.ResetColor();
     }
  } while (optionRead != "m" || optionRead != "y");
}

3 个答案:

答案 0 :(得分:8)

所以将差异作为代表传递

private void DoASearch(Action a)
{
    string optionRead = string.Empty;
    do
    {
        Console.WriteLine("\nPress \"Y\" to Continue ,\"M\" For Main Menu\n");
        Console.Write("Your Choice : ");
        optionRead = Console.ReadLine().ToLower();
        if (optionRead == "y")
        {
            if(a != null)
            {
                a();
            }
        }
        if (optionRead == "m")
        {
            m.SelectOption();
        }
        else
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("\nInvalid Option.Enter M or Y\n");
            Console.ResetColor();
        }
    } while (optionRead != "m" || optionRead != "y");
}

然后

DoASearch(SearchData);

答案 1 :(得分:0)

你应该做的是通过制作两个相等函数之间所有差异的参数来参数化方法。

E.g。

private void Repeat(bool add) // True when adding, false when searching
{
    ...
    if (add)
    { 
        AddData();
    }
    else
    {
        SearchData();
    } 
}

根据bool add使用if语句。

顺便说一下,最好使用枚举而不是布尔值。

此外,在您的情况下(作为消费者写入的解决方案),代表就足够了。 使用我的解决方案中的参数是一种更通用的解决方案。

答案 2 :(得分:0)

您可以将布尔变量传递给方法,以表示它是否应该执行Search Data();或添加数据();。

相关问题