C# 我不断地犯错误;非静态字段、方法或属性需要对象引用;
可能重复:C# 我不断地犯错误;非静态字段、方法或属性需要对象引用;,c#,visual-studio-2008,C#,Visual Studio 2008,可能重复: 我正在努力掌握编程,并且刚刚开始学习C#,所以首先,我要为我可能问了一个可能已经回答了数百次的非常基本的问题而道歉。然而,我似乎无法理解答案,也无法将答案与我正在尝试做的事情联系起来 我不断得到“非静态字段、方法或属性‘FirstConsoleApplication.Program.function(string)’需要对象引用” 有人能指出我在哪里失去了这个吗?我正在使用VisualStudio2008 namespace FirstConsoleApplication {
我正在努力掌握编程,并且刚刚开始学习
C#
,所以首先,我要为我可能问了一个可能已经回答了数百次的非常基本的问题而道歉。然而,我似乎无法理解答案,也无法将答案与我正在尝试做的事情联系起来
我不断得到“非静态字段、方法或属性‘FirstConsoleApplication.Program.function(string)’需要对象引用”
有人能指出我在哪里失去了这个吗?我正在使用VisualStudio2008
namespace FirstConsoleApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Type in an integer vale");
string num;
num = Console.ReadLine();
string result1 = function1(num);
Console.WriteLine(result1);
Console.ReadLine();
}
string function1(string x)
{
Int32 isnumber = 0;
bool canConvert = Int32.TryParse(x, out isnumber);
string returnValue;
if (canConvert == true)
{
int val3 = Int32.Parse(x);
switch (val3)
{
case 50:
returnValue = "yep its 50";
break;
case 51:
returnValue = "hmmm.... its 51... what are you gonna do about that??";
break;
case 52:
returnValue = "lets not get sloppy now...";
break;
default:
returnValue = "nope, its definately something else";
break;
};
}
else
{
returnValue = "Thats not a number";
};
return returnValue;
}
}
}您需要将函数声明为静态:
static string function1(string x)
{
...
}
在您的示例中,当您创建一个类似于
Program
的类时,您只能在首先声明该类的实例时调用非静态方法。静态方法不需要程序
类的实例。在您的示例中,您不需要担心任何属性或类变量,因此将函数声明为static是有意义的。您必须将static关键字放在function1前面,如
static string function1(string x)
Main()函数是静态的(每个类一个),而function1()函数不是静态的(每个实例一个)。在“字符串函数1(字符串x)”之前添加“static”应该可以解决这个问题。完成代码
namespace FirstConsoleApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Type in an integer vale");
string num;
num = Console.ReadLine();
string result1 = function1(num);
Console.WriteLine(result1);
Console.ReadLine();
}
static string function1(string x)
{
Int32 isnumber = 0;
bool canConvert = Int32.TryParse(x, out isnumber);
string returnValue;
if (canConvert == true)
{
int val3 = Int32.Parse(x);
switch (val3)
{
case 50:
returnValue = "yep its 50";
break;
case 51:
returnValue = "hmmm.... its 51... what are you gonna do about that??";
break;
case 52:
returnValue = "lets not get sloppy now...";
break;
default:
returnValue = "nope, its definately something else";
break;
};
}
else
{
returnValue = "Thats not a number";
};
return returnValue;
}
}
}
你在右边送行吗,上面写着“相关的”?有一群人有同样的问题,他们已经得到了可以帮助的答案?为这个问题添加答案的人感到羞耻。
Console.WriteLine(“输入整数值”)
应该是,Console.WriteLine(“键入整数值”)代码>。。。就这么说吧!你可能应该在上一个答案中将此作为一个编辑。当然,但盖伊说他是初学者,所以我给了他多种解决方案谢谢!哇,没想到这么快就能得到答案!我还没有很快了解“static”的用法,所以我想我需要仔细阅读一下。