【发布时间】:2014-02-01 13:17:54
【问题描述】:
在我上次编译时,我收到以下构建错误:
"非静态字段、方法或 属性...”
然后是我的Main() 中包含的所有项目的列表。
以前,它显示为static Main() {,但直到我将其更改为public Main() {,我才能消除错误。
我不记得在这开始发生之前我做的最后一件事(这是昨晚深夜),但我确实相信我在尝试引用主表单上的字段项目时 static void recalcTotals() 搞砸了 - 我仍然没有弄清楚,但这是一个单独的问题。
请注意,这是我的第一个 C# 程序。下面基本上是我的代码:
namespace Play_XXX
{
public partial class Main : Form
{
// Enable moveability
private const int WM_NCHITTEST = 0x84;
private const int HTCLIENT = 0x1;
private const int HTCAPTION = 0x2;
// Handling the window messages
protected override void WndProc(ref Message message) {
base.WndProc(ref message);
if (message.Msg == WM_NCHITTEST && (int)message.Result == HTCLIENT)
message.Result = (IntPtr)HTCAPTION;
}
public Main() {
InitializeComponent();
// Handle all auto-formatting textboxes
txt1.Leave += new EventHandler(validateInput);
txt2.Leave += new EventHandler(validateInput);
txt3.Leave += new EventHandler(validateInput);
txt4.Leave += new EventHandler(validateInput);
txt5.Leave += new EventHandler(validateInput);
txt6.Leave += new EventHandler(validateInput);
txt7.Leave += new EventHandler(validateInput);
txt8.Leave += new EventHandler(validateInput);
txt9.Leave += new EventHandler(validateInput);
txt10.Leave += new EventHandler(validateInput);
txt11.Leave += new EventHandler(validateInput);
}
private void Main_Load(object sender, EventArgs e) {
//TODO: Reference function to clear all input forms
}
static decimal? trueAmount(string testValue) {
decimal preOut;
//TODO: RegEx to remove all except digits?
if (testValue != null && testValue != "")
testValue = testValue.Replace(",", "").Replace("$", "");
else
testValue = "0";
//Return value
if (decimal.TryParse(testValue, out preOut))
return preOut;
else
return null;
}
void validateInput(object sender, EventArgs e) {
TextBox subjBox = (sender as TextBox);
decimal? trueVal = trueAmount(subjBox.Text);
//Check if this is a number
if (trueVal.HasValue) {
subjBox.Text = trueVal.Value.ToString("C");
subjBox.BackColor = Color.FromArgb(86, 86, 86);
subjBox.ForeColor = Color.FromArgb(208, 210, 211);
recalcTotals();
}
else {
subjBox.BackColor = Color.FromArgb(255, 200, 200);
subjBox.ForeColor = Color.Maroon;
}
}
static void recalcTotals() {
//TODO: How the fxck do your reference form controls
}
private void btnClose_Click(object sender, EventArgs e) {
Close();
}
}
}
【问题讨论】:
-
而错误发生在哪一行?看起来这个错误是不言自明的。
-
首先要了解:编译时错误和异常(在执行时抛出)是非常非常不同的。接下来,您需要将您的类从
Main重命名为其他名称,因为您需要一个名为Main的静态方法 作为入口点。我还强烈建议您在开始编写 GUI 之前尝试使用简单的控制台应用程序来掌握 C# 语言的核心部分。 -
main 上的返回类型是否需要 void?静态无效主要?另外 validateInput 看起来可能缺少静态减速。
-
@tnw
Main()内的每一行都会出现错误。我试图弄清楚为什么在使用Main()作为static创建程序时突然发生这种情况。 -
请不要使用
Main来表示可执行文件的入口点以外的任何内容。如果你这样做,你只是在自找麻烦。
标签: c# class main static-methods