类、结构或接口成员声明中的无效标记“="c# [英] Invalid token '=' in class, struct, or interface member declaration c#

查看:46
本文介绍了类、结构或接口成员声明中的无效标记“="c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这对人们来说可能是一个简单的问题,但我不明白为什么会发生这种情况.这是我的第一个代码:

this may be a simple question for people, but I can't see why this is occurring. here is my code 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 在分配符号 (=) 上给出无效令牌错误(根据标题),我不明白为什么.任何人都可以解释一下吗?

now Visual studio is giving the Invalid token error on the assignment sign (=) (as per the title), and I can not see why. can anyone shed light on this please?

我想要做的是将生命值的整数设置为 100,每次角色受到伤害时,生命值都会减少.谢谢大家.

What I'm trying to do is set the int of Health to 100, and each time a character takes damage, then Health is decreased. Thanks all.

我使用的是 Visual Studio 2013 v12.0.40629.00 更新 5

I'm using Visual Studio 2013 v12.0.40629.00 update 5

推荐答案

为自动实现的属性设置默认值仅适用于 C# 版本 6 及更高版本.在版本 6 之前,您必须使用构造函数并在那里设置默认值:

Settting a default-value for auto-implemented properties is only available from C#-version 6 and upwards. Before Version 6 you have to use the constructor and set the default-value there:

public class PlayerCharacter {
    public int Health { get; private set; }

    public PlayerCharacter()
    {
        this.Health = 100;
    }
}

要为 VS2013 启用编译器,您可以使用 这种方法.

To enable the compiler for VS2013 you may use this approach.

这篇关于类、结构或接口成员声明中的无效标记“="c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆