字段初始值设定项无法引用非静态字段,方法或属性,设置变量

时间:2017-07-06 01:22:16

标签: c#

这里的编码爱好者/爱好者,C#的新手,试图用语言包围我,并且已经在这个问题上撞墙了几天。尝试在这个网站上搜索以及在msdn上阅读关于这个错误的文档,以及有关类,字段,初始化等的文档。如果这对其他人来说是显而易见的抱歉,但我已经把我的大脑绑在了试图理解这个错误的结。

我正在编写一个基本的MUD游戏(在命令行中运行基于文本的RPG)作为我的第一个C#程序,当我尝试访问怪物统计数据时,我遇到了一个问题(我和#39; ve放入一个名为" Bestiary,"的不同命名空间,它将包含所有怪物的统计数据作为他们自己的类。我尝试了几种不同的方法,但是无法在没有错误的情况下编译程序。

using System;
using System.Collections;
using Bestiary;

//Battle system is contained in this namespace.

class Combat(string playerName)
{
  public int[] playerStats= new int[] { 25, 10};
  public int[] monsterStats= new int[] { 10, 10};

  string playerName = playerName;
  Slime s = new Slime();
  string monsterName = s.Name();
...

//Bestiary section being referenced in Combat
using System;
using System.Collections;

namespace Bestiary
{
    //List of Monsters and their stats
    class Slime
    {
        private string name = "Slime";
        public string Name
        {
            get { return name; }

            set { name = value; }
        }

        private int hp = 10;
        public int HP
        {
            get { return hp; }

            set { hp = value; }
        }

        private int atk = 1;
        public int ATK
        {
            get { return atk; }

            set { atk = value; }
        }

    }

当我尝试编译这个时,我得到错误的行#34; string monsterName = s.Name();"。

1 个答案:

答案 0 :(得分:2)

你应该像这样引用你的粘液名称:

  string monsterName = s.Name;

属性专门设计为允许您将逻辑放在getset'方法'同时保留阅读或写字段的语法。

另外,将代码放在构造函数中:

class Combat
{
  public int[] playerStats = new int[] { 25, 10};
  public int[] monsterStats = new int[] { 10, 10};
  string playerName;
  string monsterName;

  public Combat(string playerName) 
  {
    this.playerName = playerName;
    Slime s = new Slime();
    monsterName = s.Name;
  }
}

除此之外,我建议您利用var

的用法
  Slime s = new Slime();

将成为

  var slime = new Slime();

此外,无需直接声明支持字段。使用此:

public string Name { get; set; } = "Slime";

祝C#好运。