嵌入式语句不能是声明或带标签的语句

hus*_*aki 52 c# model-view-controller claims-based-identity

我正在尝试使用声明身份asp.net创建用户我在创建声明身份用户时遇到此错误.

  ApplicationUser user = new ApplicationUser { 
                        EmailConfirmed = true, 
                        UserName = model.myUser.Email,
                        Email = model.myUser.Email ,
                        PhoneNumber = model.myUser.PhoneNumber,
                        PhoneNumberConfirmed = true,
                        UserImagePath = model.myUser.UserImagePath,
                        FirstName= model.myUser.FirstName,
                        LastName = model.myUser.LastName,
                        DateOfBirth = model.myUser.DateOfBirth,
                        Culture = model.myUser.Culture,
                        Role = model.myUser.Role
                    };
Run Code Online (Sandbox Code Playgroud)

但是当代码是

var user= new ApplicationUser { 

                            UserName = model.myUser.Email,
                            Email = model.myUser.Email ,

                        };
Run Code Online (Sandbox Code Playgroud)

它工作得很好,所以我想知道出了什么问题

fel*_*x-b 130

您在发布的代码之前有一个声明(例如ifwhile),没有花括号.

例如:

if (somethingIsTrue) 
{    
   var user= new ApplicationUser { 
       UserName = model.myUser.Email,
       Email = model.myUser.Email ,
   };
}
Run Code Online (Sandbox Code Playgroud)

是正确的,但代码如下:

if (somethingIsTrue) 
   var user = new ApplicationUser { 
      UserName = model.myUser.Email,
      Email = model.myUser.Email ,
   };
Run Code Online (Sandbox Code Playgroud)

将导致CS1023:嵌入式语句不能是声明或标签声明.

UPDATE

根据@codefrenzy,原因是新声明的变量将立即超出范围,除非它被包含在块语句中,可以从中进行访问.

但是,编译将通过以下情况.

如果只初始化类型的新实例,则不声明新变量:

if (somethingIsTrue) 
   new ApplicationUser { 
       UserName = model.myUser.Email,
       Email = model.myUser.Email ,
   };
Run Code Online (Sandbox Code Playgroud)

或者如果为现有变量赋值:

ApplicationUser user;

if (somethingIsTrue) 
   user = new ApplicationUser { 
       UserName = model.myUser.Email,
       Email = model.myUser.Email ,
   };
Run Code Online (Sandbox Code Playgroud)


Mel*_*den 10

我刚刚遇到了这个错误,解决方法是在代码前面的 if 中添加一个大括号,然后再次将其删除。Visual Studio 脸部 OTD。

  • 这个答案不值得投反对票。有时会在不应该发生的情况下(未声明新变量时)发生此错误。当 VS 做出这样意想不到的事情时,这样的解决方案可以很好地修复。对于我们来说,重新启动 VS 有助于解决这个问题。 (4认同)