Using delegates in C#

前端 未结 5 553
深忆病人
深忆病人 2021-01-30 04:50

In C# language and .NET framework, could you help me with understanding delegates? I was trying to check some code, and found that the results I received were unexpected for me.

5条回答
  •  一向
    一向 (楼主)
    2021-01-30 05:28

    You need to pass in I to your function so that I.ToString() can be executed at the appropriate time (instead of at the time function is created).

    class Program
    {
        public static int I = 0;
    
        static Func del = num => num.ToString();
    
        static void Main(string[] args)
        {
            I = 10;
            Console.WriteLine("{0}", del(I));
        }
    }
    

提交回复
热议问题