事件返回null.并在触发事件时抛出未设置为实例的对象引用 [英] Event returns null. and throws object reference not set to instance when event is triggered

查看:72
本文介绍了事件返回null.并在触发事件时抛出未设置为实例的对象引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我对活动和代表有疑问.基本上我在相同的解决方案下有两个项目.一个项目是服务器,另一个项目是客户端.客户表单包含一个用于登录和登录按钮的文本框,一个丰富的文本框和用于耳语的按钮.现在,当用户单击耳语时,必须使用该消息更新向其发送消息的客户端的RTB,但在我的情况下,我收到一个例外,说对象未设置为实例.服务器和客户端的代码如下

客户代码

Hello everyone,

I have an problem with events and delegates. Basically i have two projects under same solution. One project is the server and other is the client. The client form contains a textbox for login and login button, rich textbox and button for whisper. Now when the user clicks on whisper the RTB of the client to whom message is sent has to be updated with the message but in my case i am recieving an exception saying object not set to instance. The code for server and client are has follows

Client code

namespace ChatClient
{
    [CallbackBehavior(UseSynchronizationContext = false)]
    public partial class Client : Form,IChatCallback
    {
        public delegate void ReceiveMsg(string sender, string message);
        public event ReceiveMsg Receivemessage;

        IChat chatter = null;
        DuplexChannelFactory<ichat> connect;
        InstanceContext instanceContext = null;

        
        public string CurrentUser;
        public Client()
        {
            InitializeComponent();
            
        }

        

        private void login_btn_Click(object sender, EventArgs e)
        {
            //CallBackHandler instance = new CallBackHandler();
            //instanceContext = new InstanceContext(new CallBackHandler());
            Client instance = new Client();
            instanceContext = new InstanceContext(new Client());
          
            connect = new DuplexChannelFactory<ichat>(instanceContext, "TcpBinding");
            chatter = connect.CreateChannel();
            
            if (!string.IsNullOrEmpty(login_txt.Text))
            {
                CurrentUser = login_txt.Text;
                chatter.JoinChat(CurrentUser);
               
            }
            else
            {
                MessageBox.Show("Please Enter Valid UserName", "WARNING", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void whispher_btn_Click(object sender, EventArgs e)
        {
            
            chatter.SendMessage(login_txt.Text, rtxt_message.Text);
            //Trigger event
            Receivemessage(login_txt.Text, rtxt_message.Text);
            //after execution of this statement it throws object reference not set
            //to the instance
                      
            
        }



        #region IChatCallback Members

        public void ReceiveMessage(string from, string message)
        {
            
             rtxt_message.AppendText("hellO");
            
        }
</ichat></ichat>



服务器代码



Server code

<pre lang="c#">namespace WCFChat
{
    [ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall,ConcurrencyMode=ConcurrencyMode.Reentrant)]
    class ChatServer:IChat
    {
        //public delegate void ReceiveMsg(string sender, string message);
        //public event ReceiveMsg Receivemessage;

        IChatCallback callback = null;
        Client cs = new Client();
        public static Dictionary<string,> ListofUsers = new Dictionary<string,>();
        public void JoinChat(string username)
        {
            callback = OperationContext.Current.GetCallbackChannel<ichatcallback>();
            if (CheckUserExists(username) == true)
            {
                ListofUsers.Add(username, callback);
                
            }
            else
            {
                MessageBox.Show("Username already exixts!: Please select different Name");
            }
            ListofUsers.ToArray();
            
        }

        public void SendMessage(string sender, string message)
        {
            foreach (string str in ListofUsers.Keys)
            {
                if (str == "abc")
                {
                    
                    IChatCallback icall = ListofUsers[str];
                    icall.ReceiveMessage(sender,message);
                    //registering for the event on client side
                    cs.Receivemessage+=new Client.ReceiveMsg(icall.ReceiveMessage);
                    
                    
                }
            }
        }

        public void LeaveChat(string name)
        {
        }

        //public string[] GetOnlineUsers()
        //{
        //    return ;
        //}

        public bool CheckUserExists(string username)
        {
            foreach (string name in ListofUsers.Keys)
            {
                if(username.Equals(name,StringComparison.OrdinalIgnoreCase))
                     return false;
            }
            return true;
        }
    }
}</ichatcallback>

推荐答案

很难从该代码片段中分辨出来,但是如果
It''s difficult to tell from that code fragment, but if
rtxt_message.AppendText("hellO");

导致事件被触发,那么您需要做两件事检查:
1)是否将rtxt_message设置为您的类的实例?
2)在AppendText中,您是否在触发事件处理程序之前先对其进行检查?
我的事件触发器的默认格式为:

causes an event to be fired then there are two thing you need to check:
1) Is rtxt_message set to an instance of your class?
2) In AppendText, do you check for an event handler before triggering it?
My default format for an event trigger is:

public event EventHandler Changed;

protected virtual void OnChanged(EventArgs e)
   {
   EventHandler eh = Changed;
   if (eh != null)
      {
      eh(this, e);
      }
   }

如果您在尝试触发事件之前未检查处理程序,则将获得null引用异常.

如果这样做没有帮助,那么您将不得不为我们提供更多信息,或者使用断点并单步进入每一行,直到找到空值为止.

If you do not check for an handler before trying to trigger the event, you will get a null reference exception.

If this doesn''t help, then you are going to have to either give us better information, or use a breakpoint and single step into each line until you find the null value.


这篇关于事件返回null.并在触发事件时抛出未设置为实例的对象引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆