C# 在声明之前不能使用局部变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17936325/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot use local variable before it is declared
提问by user1084113
I am trying to create a function but I'm getting an error message.
我正在尝试创建一个函数,但收到一条错误消息。
public int[] genericSearch(int searchWidth, int startingRadius, int width, int height, Bitmap bitmap)
{
//Generic function for finding the best path from a certain range
if (startingRadius == -1)
startingRadius = bitmap.Height() / 2;
Cannot use local variable 'startingRadius' before it is declared.
不能在声明之前使用局部变量 'startingRadius'。
The same problem occurs for the bitmap variable as well. Normally in c++ this type of declaration would work; however, I am unsure why it is not working here.
同样的问题也发生在位图变量上。通常在 C++ 中,这种类型的声明会起作用;但是,我不确定为什么它在这里不起作用。
回答by Kevin
You are missing a closing brace for your method but otherwise this code can compile on my machine... (changed Height to a property as well)
您的方法缺少右括号,否则此代码可以在我的机器上编译...(也将 Height 更改为属性)
public int[] genericSearch(int searchWidth, int startingRadius, int width, int height,Bitmap bitmap)
{
//Generic function for finding the best path from a certain range
if (startingRadius == -1)
startingRadius = bitmap.Height / 2;
}
回答by Stephen
It sounds like you have a misplaced }
or misspelled variable names. I can't really tell without seeing the full code.
听起来你有一个错位}
或拼写错误的变量名。如果没有看到完整的代码,我真的无法判断。
The error message is basically telling you that you have a local variable that you are trying to use which has not been declared. Which suggests that the if (startingRadius == 1)
code is actually inside a different method than the method you have declared.
该错误消息基本上是在告诉您,您有一个您正在尝试使用的未声明的局部变量。这表明if (startingRadius == 1)
代码实际上位于与您声明的方法不同的方法中。
回答by gunwin
In visual studio. Sometimes when you declare a variable again (a second time). It will give this error. For example, this will sometimes throw the exception you mentioned:
在视觉工作室。有时当你再次声明一个变量时(第二次)。它会给出这个错误。例如,这有时会抛出您提到的异常:
1. int startingRadius = 0;
2. startingRadius = 5; <-- Exception thrown here.
3.
4. int startingRadius = 0;
Obviously this is incorrect anyway. So removing the second declaration (on line 4) will solve the problem.
显然,无论如何这是不正确的。因此删除第二个声明(在第 4 行)将解决问题。
Note: The exception you would ordinarily expect would be A local variable named 'startingRadius' is already defined in this scope
. But for some reason, the exception you mentioned is shown sometimes.
注意:您通常期望的例外是A local variable named 'startingRadius' is already defined in this scope
. 但是由于某种原因,有时会显示您提到的异常。