![](/img/trans.png)
[英]C# - invalid token '' in class struct or interface member declaration
[英]Invalid token '=' in class, struct, or interface member declaration c#
对于人们来说,这可能是一个简单的问题,但我看不出为什么会发生这种情况。 这是我的代码1st:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GameCore
{
public class PlayerCharacter
{
public void Hit(int damage)
{
Health -= damage;
if (Health <= 0)
{
IsDead = true;
}
}
public int Health { get; private set; } = 100;
public bool IsDead{ get; private set; }
}
}
现在Visual Studio在赋值符号(=)上给出了无效令牌错误(按照标题),我不明白为什么。 任何人都可以阐明这一点吗?
我想做的是将生命值的int设置为100,并且每次角色受到伤害时,生命值都会降低。 谢谢大家
我正在使用Visual Studio 2013 v12.0.40629.00更新5
仅在C#版本6及更高版本中才可以为自动实现的属性设置默认值。 在版本6之前,您必须使用构造函数并在其中设置默认值:
public class PlayerCharacter {
public int Health { get; private set; }
public PlayerCharacter()
{
this.Health = 100;
}
}
要为VS2013启用编译器,您可以使用此方法 。
似乎由于MSBuild版本导致此错误,MSBuild的旧版本只能编译C#版本4,而您的代码以C#版本6格式编写(为属性设置默认值)。
使用C#版本6编写代码的示例:
public static string HostName { get; set; } = ConfigurationManager.AppSettings["RabbitMQHostName"] ?? "";
为了使MSBuild编译代码,您需要以C#4样式编写
public static string HostName { get; set; }
public SomeConstructor()
{
HostName = ConfigurationManager.AppSettings["RabbitMQHostName"] ?? "";... }
要么
public static string HostName
{
get
{
return ConfigurationManager.AppSettings["RabbitMQHostName"] ?? "";
}
}
希望能帮助到你
答案是:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GameCore
{
public class PlayerCharacter
{
public int Health { get; private set; }
public PlayerCharacter()
{
this.Health = 100;
}
public void Hit(int damage)
{
Health -= damage;
if (Health <= 0)
{
IsDead = true;
}
}
public bool IsDead{ get; private set; }
}
}
使构造函数具有()而不是PLayerCharacter {等。
多亏所有,回到我的洞里去了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.