嵌入式语句不能是声明或标记语句

Embedded statement cannot be a declaration or labeled statement

我正在尝试使用声明身份创建用户 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
                    };

但是当代码是

var user= new ApplicationUser { 

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

                        };

它运行完美,所以我想知道哪里出了问题

您在发布的代码之前有一个语句(例如,ifwhile,没有大括号。

例如:

if (somethingIsTrue) 
{    
   var user= new ApplicationUser { 
       UserName = model.myUser.Email,
       Email = model.myUser.Email ,
   };
}

是正确的,但是下面的代码:

if (somethingIsTrue) 
   var user = new ApplicationUser { 
      UserName = model.myUser.Email,
      Email = model.myUser.Email ,
   };

将导致 CS1023:嵌入语句不能是声明或标记语句。

更新

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

以下情况编译通过

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

if (somethingIsTrue) 
   new ApplicationUser { 
       UserName = model.myUser.Email,
       Email = model.myUser.Email ,
   };

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

ApplicationUser user;

if (somethingIsTrue) 
   user = new ApplicationUser { 
       UserName = model.myUser.Email,
       Email = model.myUser.Email ,
   };

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