class、结构或接口成员声明中的无效标记“=”c#

Invalid token '=' in class, struct, or interface member declaration c#

这对人们来说可能是一个简单的问题,但我不明白为什么会这样。这是我的第一个代码:

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 在赋值符号 (=) 上给出无效令牌错误(根据标题),我不明白为什么。任何人都可以阐明这一点吗?

我想做的是将 Health 的 int 设置为 100,每当角色受到伤害时,Health 就会减少。谢谢大家

我正在使用 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 启用编译器,您可以使用 this approach

答案是:

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{ 等

感谢大家,回到我的洞里去。

看起来这个错误是由于您的 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"] ?? "";
            }
        }

希望对您有所帮助