侧边栏壁纸
博主头像
Tony's Blog博主等级

行动起来,coding

  • 累计撰写 83 篇文章
  • 累计创建 58 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录
c#

System.ArgumentException_“该委托必须有一个目标(且仅有一个目标)。”

Tony
2024-02-23 / 0 评论 / 0 点赞 / 8 阅读 / 3426 字

本文链接: https://blog.csdn.net/lishuangquan1987/article/details/135149899

正常情况

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BeginInvokeTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Test t = new Test();
            t.Printed += T_Printed;
            t.Call("fjds");
            Console.ReadLine();
        }

        private static void T_Printed(string obj)
        {
            Console.WriteLine("T_Printed:" + obj);
        }
    }
    public class Test
    {
        public event Action<string> Printed;
        public void Call(string s)
        {
            this.Printed?.BeginInvoke(s, null, null);
        }
    }
}

此时正常输出 fjds

出错情况

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BeginInvokeTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Test t = new Test();
            t.Printed += T_Printed;
            t.Printed += T_Printed2;
            t.Call("fjds");
            Console.ReadLine();
        }

        private static void T_Printed2(string obj)
        {
            Console.WriteLine("T_Printed2:" + obj);
        }

        private static void T_Printed(string obj)
        {
            Console.WriteLine("T_Printed:" + obj);
        }
    }
    public class Test
    {
        public event Action<string> Printed;
        public void Call(string s)
        {
            this.Printed?.BeginInvoke(s, null, null);
        }
    }
}

这个仅仅比上面多绑定了一个方法就报错了。
1-goka.png

将上述的 Printed 由事件改成委托,一样报错

结论

使用 事件或者委托BeginInvoke 需要注意:如果事件或者委托可能绑定多个方法,不能用BeginInvoke,需要使用Invoke

0

评论区