事件争论问题。 [英] Event Argument Problems.

查看:55
本文介绍了事件争论问题。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在调试中得到这些回报并且不明白为什么:



1)

I keep getting these returns in debug and don't understand why:

1)

Error   7   Argument 2: cannot convert from 'NEOPETS_GUI.classes.communications.WrongPassword' to 'NEOPETS_GUI.classes.communications.Response' c:\users\cassandra\documents\visual studio 2013\projects\neopets_gui\neopets_gui\classes\transmition.cs 224 43  NEOPETS_GUI





2)



2)

Error   5   Argument 2: cannot convert from 'NEOPETS_GUI.classes.communications.WrongUserName' to 'NEOPETS_GUI.classes.communications.Response' c:\users\cassandra\documents\visual studio 2013\projects\neopets_gui\neopets_gui\classes\transmition.cs 219 43  NEOPETS_GUI





感谢您的帮助:)





I appreciate your help :)

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

namespace NEOPETS_GUI.classes.communications
{
    public class EOL : EventArgs
    {
        private bool status;

        public EOL(bool status)
        {
            this.status = status;
        }

        public bool Status
        {
            get
            {
                return status;
            }
        }
    }

    public class WrongUserName : EventArgs
    {
        private bool status;

        public WrongUserName(bool status)
        {
            this.status = status;
        }

        public bool Status
        {
            get
            {
                return status;
            }
        }
    }
    public class WrongPassword : EventArgs
    {
        private bool status;

        public WrongPassword(bool status)
        {
            this.status = status;
        }

        public bool Status
        {
            get
            {
                return status;
            }
        }
    }
    public class LoggedOut : EventArgs
    {
        private bool status;

        public LoggedOut(bool status)
        {
            this.status = status;
        }

        public bool Status
        {
            get
            {
                return status;
            }
        }
    }
    public class Offline : EventArgs
    {
        private bool status;

        public Offline(bool status)
        {
            this.status = status;
        }

        public bool Status
        {
            get
            {
                return status;
            }
        }
    }
    public class Cookies : EventArgs
    {
        private string data;

        public Cookies(string data)
        {
            this.data = data;
        }

        public string Data
        {
            get
            {
                return data;
            }
        }
    }

    public class Response : EventArgs
    {
        private string data;

        public Response(string data)
        {
            this.data = data;
        }

        public string Data
        {
            get
            {
                return data;
            }
        }
    }

    class transmition
    {


        public delegate void Response_Handler(Object myobject, Response source);
        public event Response_Handler OnResponse;

        public delegate void Cookie_Handler(Object myobject, Cookies cookies);
        public event Cookie_Handler OnCookies;

        public delegate void Offline_Handler(Object myobject, Offline true_false);
        public event Offline_Handler OnOffline;

        public delegate void LoggedOut_Handler(Object myobject, LoggedOut true_false);
        public event LoggedOut_Handler OnLoggedOut;

        public delegate void EOL_Handler(Object myobject, EOL true_false);
        public event EOL_Handler ATEOL;

        public delegate void WrongPassword_Handler(Object myobject, Response true_false);
        public event WrongPassword_Handler OnWrongPassword;

        public delegate void WrongUserName_Handler(Object myobject, Response true_false);
        public event WrongUserName_Handler OnWrongUserName;


        public int Navigate(string page = "", string formparams = "", string cookieheader = "")
        {
            try
            {
                using (var client = new WebClient())
                using (var stream = client.OpenRead("http://www.google.com"))
                {
                    // Do Nothing :)
                }
            }
            catch
            {
                Offline connected = new Offline(false);
                OnOffline(this, connected);
                return 0;
            }

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://www.neopets.com/" + page);
            req.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0";

            string src = "";

            if (cookieheader != "")
            {
                req.Headers.Add("Cookie", cookieheader);
                HttpWebResponse getResponse = (HttpWebResponse)req.GetResponse();
                using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
                {
                    src = sr.ReadToEnd();
                }
            }
            else
            {
                byte[] bytes = Encoding.ASCII.GetBytes(formparams);
                req.ContentType = "application/x-www-form-urlencoded";
                req.Method = "POST";
                req.ContentLength = bytes.Length;

                using (Stream os = req.GetRequestStream())
                {
                    os.Write(bytes, 0, bytes.Length);
                }

                HttpWebResponse getResponse = (HttpWebResponse)req.GetResponse();
                cookieheader = getResponse.Headers["Set-cookie"];

                Cookies cookies = new Cookies(cookieheader);
                OnCookies(this, cookies);

                using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
                {
                    src = sr.ReadToEnd();
                }
            }

            if (src.Contains("action=\"/login.phtml"))
            {
                if (src.Contains("Blah"))
                {
                    WrongUserName wrongusername = new WrongUserName(true);
                    OnWrongUserName(this, wrongusername);
                }
                else if (src.Contains("Blah2"))
                {
                    WrongPassword wrongpassword = new WrongPassword(true);
                    OnWrongPassword(this, wrongpassword);
                }
                else
                {
                    LoggedOut loggedout = new LoggedOut(true);
                    OnLoggedOut(this, loggedout);
                }
            }

            Response source = new Response(src);
            OnResponse(this, source);

            EOL ateol = new EOL(true);
            ATEOL(this, ateol);

            return 1;
        }
    }
}

推荐答案

OnWrongPassword事件需要一个响应,但是你通过了 WrongPassword (同样对于OnWrongUserName,它需要一个响应,但你传递一个WrongUserName)。



有两种方法解决问题。您应该使用哪种,取决于您的应用程序。

The OnWrongPassword event expects a Response, but you pass a WrongPassword (same for OnWrongUserName, it expects a response but you pass a WrongUserName).

There are two ways to solve the problem. Which you should use, depends on your application.


  1. 您可以通过更改创建委托的行的类型来解决此问题:


  1. You can solve this by changing the type at the lines where you create the delegate:
public delegate void WrongPassword_Handler(Object myobject, WrongPassword true_false);
public event WrongPassword_Handler OnWrongPassword;
 
public delegate void WrongUserName_Handler(Object myobject, WrongUserName true_false);
public event WrongUserName_Handler OnWrongUserName;

  • 您也可以这样做:在您调用这些事件处理程序的行上,使用 Response 类而不是 WrongPassword WrongUserName


  • 仅因为响应源自EventArgs和WrongUserName派生自EventArgs,并不意味着它们可以互换:当你期待一个EventArgs时,它们都可以,但是签名:

    Just because a Response is derived from EventArgs, and WrongUserName is derived from EventArgs, doesn't mean they are interchangeable: they are both OK when you are expecting an EventArgs, but the signature:
    public delegate void WrongUserName_Handler(Object myobject, Response true_false);
    public event WrongUserName_Handler OnWrongUserName;



    需要Reponse类型,而不是WrongUserName:


    Requires a Reponse type, not a WrongUserName:

    WrongUserName wrongusername = new WrongUserName(true);
    OnWrongUserName(this, wrongusername);



    您可以从Response派生WrongUserName和WrongPassword,而不是EventArgs。





    顺便说一句:当你想提高它时,调用该事件不是一个好主意:如果没有注册处理程序,你将获得Null Reference例外。

    我的方式是:


    You could derive both WrongUserName and WrongPassword from Response, instead of EventArgs.

    [edit]
    BTW: It's not a good idea to just call the event when you want to raise it: if there are no handlers registered, you will get a Null Reference exception.
    The way I do it is:

    /// <summary>
    /// Event to indicate WrongPassword
    /// </summary>
    public event EventHandler WrongPassword;
    /// <summary>
    /// Called to signal to subscribers that WrongPassword
    /// </summary>
    /// <param name="e"></param>
    protected virtual void OnWrongPassword(EventArgs e)
        {
        EventHandler eh = WrongPassword;
        if (eh != null)
            {
            eh(this, e);
            }
        }



    [/ edit]


    [/edit]


    我觉得你做了很多额外的工作并且所有这些EventArguments都可以用一个简单的类和一个枚举来处理:
    I think you are doing a lot of extra work, and that all these EventArguments could be handled with one simple class and an Enum:
    namespace YourNameSpace
    {
        public enum StatusTypes
        {
            EOL,
            WrongUserName,
            WrongPassword,
            LoggedOut,
            Offline,
            Cookies,
            Response
        }
    
        public class WebEventArgs : EventArgs
        {
            public StatusTypes StatusType { private set; get; }
    
            public bool? ResultStatus { private set; get; }
    
            public string Data { private set; get; }
    
            // note use of optional parameters
            public WebEvntArgs(StatusTypes statusType, bool? resultStatus = null, string data = null)
            {
                StatusType = statusType;
                ResultStatus = resultStatus;
                Data = data;
            }
        }
    
        // Test in some appropriate context ...
    
        public event WebEvent_Handler WebEvent;
        
        protected virtual void OnWebEvent(StatusTypes statusType, WebEventArgs e)
        {
            var handler = WebEvent;
        
            if (handler == null) return;
        
            handler(statusType, e);
        }
        
        // define a Handler of type WebEvent
        public void Form1_WebEvent(StatusTypes statusType, WebEventArgs webData)
        {
            // if ResultStatus is null that would be rendered as an Empty String
            // so convert it to readable form
            var result = (webData.ResultStatus == null) ? "null" : webData.ResultStatus.ToString();
        
            switch (statusType)
            {
                case StatusTypes.WrongUserName:
                case StatusTypes.Cookies:
                case StatusTypes.Response:
                    MessageBox.Show(string.Format("{0} : {1} : {2}", statusType, result, webData.Data));
                    break;
                default:
                    MessageBox.Show(string.Format("{0} {1}", statusType, result));
                    break;
            }
        }
        
        // test
        private void button1_Click_1(object sender, EventArgs e)
        {
            // wire up the Handler only once !
            if (WebEvent == null) WebEvent += Form1_WebEvent;
        
            var wrongUserData = "a stranger";
            var cookieData = "chocolate-chip";
            var responseData = "nobody home";
            var testBool = true;
        
            // test with both parameters supplied
            OnWebEvent(StatusTypes.WrongUserName, new WebEventArgs(StatusTypes.WrongUserName, true, data: wrongUserData));
        
            // test with bool ResultStatus optional parameter omitted
            // since the last parameter is supplied, we have to use the
            // last parameter name followed by a colon in order to compile
            OnWebEvent(StatusTypes.Cookies, new WebEventArgs(StatusTypes.Cookies, data: cookieData));
        
            OnWebEvent(StatusTypes.Response, new WebEventArgs(StatusTypes.Response, data: responseData));
        
            // test without second and third parameters
            OnWebEvent(StatusTypes.EOL, new WebEventArgs(StatusTypes.EOL));
        }
    }


    这篇关于事件争论问题。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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