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

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

问题描述

这可能是一个简单的问题,但我不明白为什么会发生这种情况。这里是我的代码第一:

  using System; 
使用System.Collections.Generic;
使用System.Linq;
使用System.Text;
使用System.Threading.Tasks;

命名空间GameCore
{
public class PlayerCharacter
{

public void Hit(int damage)
{
健康 - =损害;

if(Health <= 0)
{
IsDead = true;
}
}

public int Health {get;私人设置; } = 100;
public bool IsDead {get;私人设置; }


$ b $ / code>

现在Visual Studio正在为赋值符号(=)(根据标题)无效令牌错误,我看不出为什么。任何人都可以阐明这一点吗?



我要做的是将生命值设置为100,并且每次角色受到伤害时,健康就是降低。感谢所有。



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

解决方案

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

  public class PlayerCharacter {
public int Health {get;私人设置; }

public PlayerCharacter()
{
this.Health = 100;


code $


要启用VS2013的编译器,可以使用这种方法


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; }

    }
}

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?

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.

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

解决方案

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;
    }
}

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

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

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