无法从另一个类c#调用变量
本文关键字:调用 变量 另一个 | 更新日期: 2023-09-27 18:20:33
我的c#应用程序中有以下类:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace Citrix_Killer
{
public static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
public static void Main()
{
string name = Myfunc.userName();
List<string> servers = Myfunc.get_Servers();
string[] session = Myfunc.get_Session(servers, name);
string sessID = session[0];
string server = session[1];
string sessName = session[2];
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
其中,sessId、server和sessName都具有适当的值。在我的Form1.Designer中,我想调用这些细节来显示在表单上(按钮1的文本):
//
// button1
//
this.button1.Location = new System.Drawing.Point(12, 12);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = Program.sessName;
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
然而
但我看到了这个错误:类型或命名空间名称"sessName"在命名空间"Citrix_Killer"中不存在(您是否缺少程序集引用?)
当只使用sessName时,这也会失败——有人能告诉我正确的方向吗?
非常感谢
解决方案是在创建Form1
时将所需的值传递给它。例如,假设您希望访问sessID
、server
和sessName
,请更改Program.cs
:
namespace Citrix_Killer
{
public static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
public static void Main()
{
...
Application.Run(new Form1(sessID, server, sessName));
}
}
}
并更改Form1.cs
以接受其构造函数中的值
public partial class Form1 : Form
{
private readonly string _sessId;
private readonly string _server;
private readonly string _sessName;
public Form1(string sessId, string server, string sessName)
{
_sessId = sessId;
_server = server;
_sessName = sessName;
InitializeComponent();
...
}
然后你可以在你的初始化代码中引用它们:
//
// button1
//
this.button1.Location = new System.Drawing.Point(12, 12);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = _sessName;
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);