C#对象不包含方法的定义

时间:2014-09-05 16:35:05

标签: c#

我为这个愚蠢的问题道歉,但我是C#的新手,并且无法从与此错误相关的其他问题中找到帮助。

我创建了一个名为“Sender”的类,但在实例化对象时无法访问我的方法。当我尝试调用我的方法时,我得到错误:“对象不包含sendMessage的定义。”我不知道我哪里出错了。请指出我正确的方向。

感谢您的帮助!

这是我的Sender课程:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;

namespace CS5200_HW1_GUI
{
    public class Sender
    {
        private UdpClient myUdpClient;
        private IPEndPoint localEP;
        string ipAddress = "129.123.41.1";
        string _port = "12001";

        public void sendMessage()
        {

        }
       // byte[] sendBuffer = Encoding.Unicode.GetBytes(command);
       // int result = myUdpClient.Send(sendBuffer, sendBuffer.Length, localEP);

     }
 }

这是我试图调用方法的地方:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.Net;
    using System.Net.Sockets;
    using System.Net.NetworkInformation;

    namespace CS5200_HW1_GUI
    {
         public partial class Form1 : Form
         {
              //private UdpClient myUdpClient;
              IPEndPoint localEP = new IPEndPoint(IPAddress.Any, 0);
              string command = string.Empty;
              string newWord = String.Empty;
              string guess = String.Empty;
              string dashes = String.Empty;
              string newAddress = string.Empty;
              string newPort = string.Empty;
              int score = 0;
              int length = 0;
              StringBuilder sb = new StringBuilder();
              Random random = new Random();

              Sender sender = new Sender();

              private void button1_Click(object sender, EventArgs e)
              {
                   command = "NewGame";
                   sender.sendMessage(command);             //I get the error here
                   newWord = receiver.receiveMessage();
                   length = newWord.Length;
              }
        }
    }

2 个答案:

答案 0 :(得分:7)

这是因为sender既是Sender对象又是click处理程序的参数之一。

注意方法签名:

private void button1_Click(object sender, EventArgs e)

您指的是距离最近的发件人,类型为object。要解决此问题,您必须重命名或使用this进行调用。

示例:

this.sender.sendMessage()

答案 1 :(得分:4)

您正在使用参数(sender.sendMessage

调用command

sendMessage对象上唯一一个名为Sender的函数不带任何参数,因此找不到匹配的方法。

您还使用sender变量,该变量是Click方法中的变量(由于签名)。您应该使用其他名称。