繁体   English   中英

如何将此值分配给 c# 中的全局变量?

[英]How do I assign this value to a global variable in c#?

我需要将从套接字 (TCP/IP) 接收到的值分配给变量,以便我可以在表单的标签中使用它。 我在这里问是因为我一直在寻找和尝试几个小时但找不到任何东西。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;

namespace ConsoleApp1
{
class Exemys
{
        static byte[] Buffer { get; set; }
        static Socket sck;
        [STAThread]
        public static void Conectar(/*string[] args*/)
        {
            sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint localEndpoint = new IPEndPoint(IPAddress.Parse("192.168.34.230"), 5202);
            try
            {
                sck.Connect(localEndpoint);
                Console.WriteLine("Exemys connected!\r\n");
            }
            catch
            {
                Console.Write("Unable to connect to Exemys\r\n");
                Conectar(/*args*/);
            }
        while (true)
        {
            Buffer = new byte[sck.SendBufferSize];
            int bytesRead = sck.Receive(Buffer);
            byte[] formatted = new byte[bytesRead];
            for (int i = 0; i < bytesRead; i++)
            {
                formatted[i] = Buffer[i];
            }
            string mensaje = Encoding.ASCII.GetString(formatted);
            Console.Write(mensaje + "\r\n");
            
        }
    }       
}
}

这段代码写在一个类中,Form在其他地方。 我需要分配的值是mensaje ,所以我可以在表单的文本框中看到它。

首先,全局变量闻起来像一个糟糕的设计。 无论如何,您似乎在举一个ConsoleApplication的例子,但您可能有一个Windows Form Application 显然,您无法从控制台应用程序运行表单,因此只需将所有内容转换为 Windows 表单应用程序即可。

无论如何,在你有一个 Form 工作之后,你可能会改变你的代码,以便Conectar() ,实际上我们可以给一个更好的名字,比如ConnectAndGetMessage() ,来实际返回消息。 然后您从您的 Form 调用该方法,可能是在 Load 处理程序上。

简而言之,您可以执行以下操作:

class Exemys {

    public static string ConnectAndGetMessage() {
        // Here your code! ;)
        return mensaje;
    }
}

class FormWithTextbox {

    private void FormWithLabel_Load(object sender, System.EventArgs e)
    {
        Textbox1.Text = Exemys.ConnectAndGetMessage();
    }
}

请注意,这不是最佳解决方案,因为您应该将 Exemys 作为依赖项注入,无论如何,这将用于以后的改进。

关于您的代码的另一件事要指出,但您可能很快就会知道,您没有退出 while 循环,因此您可能最终会陷入无限循环。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM