我想在我的Windows窗体应用程序来创建一个对象,但如果我在构造函数创建它,然后我不能访问它在整个应用程序...(如事件)在时间1 ISN下面的代码不可用。我会很高兴收到你的来信......哪里可以在windows窗体应用程序中创建我的对象?
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;
namespace ClockApp
{
public partial class ClockApp : Form
{
public ClockApp()
{
InitializeComponent();
ClockApp Time1 = new ClockApp();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void ClockApp_Load(object sender, EventArgs e)
{
}
private void btnOk_Click(object sender, EventArgs e)
{
//ClockApp Time1 = new ClockApp();
Time1.getHour = Convert.ToInt16(txtHour.Text);
Time1.getMin = Convert.ToInt16(txtMin.Text);
Time1.getSec = Convert.ToInt16(txtSec.Text);
if(rbUniversal.Checked == true)
{
Time1.ToUniversal();
}else if(rbStandard.Checked == true)
{
Time1.ToStandard();
}
else
{
lblTime.Text = "NOT Working...";
}
}
}
}
下面的代码是我的课:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ClockApp
{
public partial class ClockApp : Form
{
// Fields
private int Hour;
private int Min;
private int Sec;
// Properties
public int getHour
{
get
{
return Hour;
}
set
{
if(value > 23 && value < 0)
{
Hour = 23;
}
else
{
Hour = value;
}
}
}
public int getMin
{
get
{
return Min;
}
set
{
if(value > 59 && value < 0)
{
Min = 59;
}
else
{
Min = value;
}
}
}
public int getSec
{
get
{
return Sec;
}
set
{
if(value > 59 && value < 0)
{
Sec = 59;
}
else
{
Sec = value;
}
}
}
// Constructors
// Methods
// ToUniversal()
public void ToUniversal()
{
lblTime.Text = Hour.ToString() + ":" + Min.ToString() + ":" + Sec.ToString();
}
// ToStandard()
public void ToStandard()
{
if(Hour > 12)
{
int[] Modifier = new int[12];
for (int i = 0; i < 12; i++)
{
Modifier[i] = i + 13;
if (Hour == Modifier[i])
{
Hour = i+1;
lblAMPM.Text = "PM";
}
}
lblTime.Text = Hour.ToString() + ":" + Min.ToString() + ":" + Sec.ToString();
}
else
{
lblAMPM.Text = "AM";
lblTime.Text = Hour.ToString() + ":" + Min.ToString() + ":" + Sec.ToString();
}
}
}
}
如果您在一个方法中定义并初始化一个对象,比如您的构造函数,那么当该方法完成执行时它就会被销毁。在c#中查找有关变量作用域的信息。 –
你有一些严肃的设计流程...为什么你的ClockApp是从Forms类派生的?而是将这些方法编写为Getters并从窗体应用程序访问它们的返回值。 –