调用委托导致错误“未分配”

时间:2018-11-27 03:16:09

标签: c# delegates

我想写在屏幕底部的操作完成后得到的屏幕结果。但是我不想在“ IF”函数中使用Console.WriteLine(),我想将其称为委托龋齿值,但它表示未赋值。 (该网站说的大部分是代码,但我不必说其他话,所以我只在这里输入:D)

namespace ConsoleApp5
{
    class program
    {
        delegate int first(int a, int b);  
        static void Main()
        {
            first beta;
            int result;
            Console.Write("insert number A: ");
            int.TryParse(Console.ReadLine(), out int a);
            if (a == 0)
            {
                Console.WriteLine("not a number");
                Environment.Exit(0);
            }

            Console.Write("insert number B: ");
            int b = int.Parse(Console.ReadLine());
            if (a == 0)
            {
               Console.WriteLine("not a number");
               Environment.Exit(0);
            }

            Console.WriteLine("plus(1) or minus (0)");  
            int c = int.Parse(Console.ReadLine());

            if (c == 1)
            {
                beta = plus;
                result = beta(a, b);  
                Console.WriteLine(result);
            }
            else if (c == 0)
            {
               beta = minus; 
               result = beta(a, b); 
               Console.WriteLine(result);
            }

            beta(); // PROBLEM HERE, I WANT TO WRITE ANSWER FROM THIS 
                    //instead of "Console.WriteLine(result);" inside function

       }

        private static int plus(int a, int b)
        {
            return a + b;
        }

        private static int minus(int a, int b)
        {
            return a - b;
        }
    }
}

示例我的意思是我想完成的任务,但是有点不同。

using System;
namespace consoleApplication4
{
  class Program{

Delegate void Message();

     static void Main (string[] args)
{

Message mes;

if (DateTime.Now.Hour < 12)
{
mes=GoodMorning;
}

else{
mes=GoodEvening;
}

mes();  //this does what i want here but in code above something is missing
Console.ReadKey();
}


private static void GoodMorning(){
console.WriteLine("Good Morning");
}
Private static void GoodEvening(){
Console.WriteLine("Good Evening");
}}}

1 个答案:

答案 0 :(得分:1)

您已经有了正确的代码来在if的两个分支中调用您的代表。因此,要使代码几乎可以正常工作,需要将调用beta的这两行移出两个分支:

    if (c == 1)
    {
       beta = plus;
    }
    else if (c == 0)
    {
       beta = minus; 
    }
    result = beta(a, b); 
    Console.WriteLine(result);

现在另一个问题仍然存在-您的if检查有3个结果(0、1,其他),但是beta仅在两种情况下分配。因此,我们还需要添加“其他”情况以及某些期望的输出(或简单地失败),switch语句比链式ifs更好地表达这种情况:

    switch (c)
    {
      case 1: beta = plus; break;
      case 0: beta = plus; break;
      default: beta = (a,b)=>""; break;
      // alternatively to fail: default: return 0;
    }
    result = beta(a, b); 
    Console.WriteLine(result);