C# 在声明 ASP.NET 之前不能使用局部变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/279748/
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 ASP.NET
提问by Matt Mitchell
I have some code like this:
我有一些这样的代码:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Save([Bind(Prefix="")]Person person)
{
String s = person.property;
/* ... */
}
But it throws the error: "Cannot use local variable 'person' before it is declared".
但它抛出错误:“在声明之前不能使用局部变量'person'”。
What simple thing am I missing?
我错过了什么简单的事情?
采纳答案by Matt Mitchell
Okay, this is just some really bizarre error - if the variable is named a particular name it does not work, for any other name it does work...
好吧,这只是一些非常奇怪的错误——如果变量被命名为一个特定的名称,它就不起作用,对于任何其他名称,它都起作用......
回答by Matt Mitchell
It is most likely that you are receiving this error because the same variable is being declared later in the same code block.
您收到此错误很可能是因为稍后在同一代码块中声明了同一变量。
According to compiler rules, a variable reference will refer to default by a matching declaration withing the same block EVEN IF THE SAME DECLARATION EXISTS OUTSIDE OF THE BLOCK IN IN LOGICAL SCOPE FLOW.
根据编译器规则,变量引用将通过具有相同块的匹配声明来引用默认值,即使相同的声明存在于逻辑范围流中的块之外。
So in short, check to see if the variable isnt being declared later on(a couple of lines down) in the same application block.
所以简而言之,检查变量是否没有在同一应用程序块中稍后(向下几行)声明。
回答by Frankie Lee
I had the same problem with a declared variable named endingYear.
我对一个名为endingYear 的声明变量有同样的问题。
Declared here:
在此声明:
public ChartData(MetricInfo metricInfo, MetricItem[] metricItems) : this()
{
int endingYear = 0;
Further along in the method this was not a problem:
在该方法中,这不是问题:
endingYear = endingDate.Year;
But when I referenced the very same varable in a Case statement I got the "Cannot use local variable before it is declared" error even thou the variable was in intelesense:
但是,当我在 Case 语句中引用完全相同的变量时,即使变量在智能感知中,我也会收到“在声明之前无法使用局部变量”错误:
case "QRTR_LAST_FULL_QRTR":
if (metricInfo.CalendarType == "CALENDAR")
{
switch (endingDate.Month)
{
case 1:
case 2:
case 3:
loopControl = 4;
endingYear = endingDate.Year - 1;
Based on Matt's result I tried changing the variable name to endYear and the problem went away. Very strange and a waste of a half hour or so. If it was not for this thread of posts it probably would have been a bigger time loss.
根据 Matt 的结果,我尝试将变量名称更改为 endYear,问题就消失了。很奇怪,浪费了半个小时左右。如果不是这个帖子,可能会浪费更多的时间。