如何获取 Hello 世界控制台应用程序并引用文本以显示在 WinForm 标签中

本文关键字:文本 引用文 引用 显示 标签 WinForm 应用程序 何获取 获取 控制台 世界 | 更新日期: 2023-09-27 17:56:42

基本上,我正在尝试将WriteLine的内容移动到WinForm中的标签框中,作为面向对象编程的介绍。 我相信我有一些语法错误,我知道我有写行的方法无效。 因此,任何帮助使其工作都是值得赞赏的。这只是我所做的尝试之一。

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 ConsoleHelloWorld.Program;

namespace WindowsFormHelloWorld
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            string words = new ConsoleHelloWorld.Program.Main(words);
            label1.Text = words;
        }
    }
}

这是我引用的代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleHelloWorld
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            string words = "hello world";
            Console.WriteLine(words);
            Console.ReadLine();
        }
    }
}

如何获取 Hello 世界控制台应用程序并引用文本以显示在 WinForm 标签中

您的words变量是局部变量,即它的作用域是声明它的方法,即Main。在该方法之外,您无法引用它。

要使变量可访问,需要使其成为公共字段(或类的属性)。如果您需要在没有该类类型的实例的情况下访问它,则应将此字段声明为 static 。那么你的代码将如下所示:

public static class Program
{
    public readonly static string Words = "hello world";
    //...   
}
假设 Windows 应用程序

项目在 Windows 应用程序窗体中具有对控制台应用程序项目的引用,您可以编写:

string words = ConsoleHelloWorld.Program.Words;
此外,您不需要启动控制台

应用程序,此外您不会设法像这样做(如果您打算同时启动控制台和 Windows 应用程序,请考虑 Cuong Le 的答案)。

让它工作了。 事实证明,我扎根不正确。 (我原以为生根的工作方式更像安卓文件结构。基本上,我创建了一个单独的类来保存 Hello World 变量,并且只是调用它来表示我是要将字符串打印到控制台还是 WinForm 应用程序。

初始代码块:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleHelloWorld
{

    public static class Program
    {
        public static class Hello
        {
            public static string words = "Hello World";
        }
       public static void Main(string[] args)
       {
           string word = ConsoleHelloWorld.Program.Hello.words;
           Console.WriteLine(word);
           Console.ReadLine();
       }
   }
}

调用类的 WinForm:

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 ConsoleHelloWorld; //Program.Hello;

namespace WindowsFormHelloWorld
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            string word = ConsoleHelloWorld.Program.Hello.words;
            label1.Text = word;
        }
    }
}

在以后的项目中,我将只保留代码在它自己的项目中由各种环境运行。