C# 字段初始值设定项不能引用非静态字段、方法或属性。1.

C# 字段初始值设定项不能引用非静态字段、方法或属性。1.,c#,xna-4.0,C#,Xna 4.0,好的,问题是我得到了两个代码,一个来自我正在阅读的书,另一个来自我写的书,它们都是相同的,让我们从这本书的代码开始 public class Game1 : Microsoft.Xna.Framework.Game { SpriteFont font; GraphicsDeviceManager graphics; SpriteBatch spriteBatch; DateTime nowDateTime =

好的,问题是我得到了两个代码,一个来自我正在阅读的书,另一个来自我写的书,它们都是相同的,让我们从这本书的代码开始

public class Game1 : Microsoft.Xna.Framework.Game
{        
         SpriteFont font;
         GraphicsDeviceManager graphics;
         SpriteBatch spriteBatch;
         DateTime nowDateTime = DateTime.Now;
         string nowString = nowDateTime.ToString();
    `   
这不会给出任何错误。。。现在关于代码,我把自己从书上写下来了

public class Game1 : Microsoft.Xna.Framework.Game
{
    SpriteFont font;
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    DateTime nowDateTime = DateTime.Now;
    string nowString = nowDateTime.ToString();
完全一样,对吗?还是我错过了一些重要的东西? 我完全不明白,我的错误就在这个主题里

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace WindowsGame4
{
     /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        SpriteFont font;
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        DateTime nowDateTime = DateTime.Now;
        string nowString = nowDateTime.ToString();

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            font = Content.Load<SpriteFont>("Spritefont1");
            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            DateTime nowDatetime = DateTime.Now;

            // TODO: Add your drawing code here

            base.Draw(gameTime);
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用Microsoft.Xna.Framework;
使用Microsoft.Xna.Framework.Audio;
使用Microsoft.Xna.Framework.Content;
使用Microsoft.Xna.Framework.GamerServices;
使用Microsoft.Xna.Framework.Graphics;
使用Microsoft.Xna.Framework.Input;
使用Microsoft.Xna.Framework.Media;
名称空间WindowsGame4
{
/// 
///这是游戏的主要类型
/// 
公共类游戏1:Microsoft.Xna.Framework.Game
{
SpriteFont字体;
图形管理器图形;
SpriteBatch SpriteBatch;
DateTime nowDateTime=DateTime.Now;
字符串nowString=nowDateTime.ToString();
公共游戏1()
{
graphics=新的GraphicsDeviceManager(此);
Content.RootDirectory=“Content”;
}
/// 
///允许游戏在开始运行之前执行任何需要的初始化。
///在这里,它可以查询任何必需的服务,并加载任何非图形化的服务
///相关内容。调用base.Initialize将枚举所有组件
///并对它们进行初始化。
/// 
受保护的覆盖无效初始化()
{
//TODO:在此处添加初始化逻辑
base.Initialize();
}
/// 
///LoadContent将在每个游戏中调用一次,并且是加载的地方
///你所有的内容。
/// 
受保护的覆盖void LoadContent()
{
//创建一个新的SpriteBatch,可用于绘制纹理。
spriteBatch=新spriteBatch(图形设备);
font=Content.Load(“Spritefont1”);
//TODO:使用此.Content在此处加载游戏内容
}
/// 
///UnloadContent将在每个游戏中调用一次,并且是卸载的地方
///所有内容。
/// 
受保护的覆盖无效UnloadContent()
{
//TODO:在此卸载任何非ContentManager内容
}
/// 
///允许游戏运行逻辑,例如更新世界,
///检查碰撞、收集输入和播放音频。
/// 
///提供计时值的快照。
受保护覆盖无效更新(游戏时间游戏时间)
{
//允许游戏退出
if(GamePad.GetState(PlayerIndex.One).Buttons.Back==ButtonState.Pressed)
这是Exit();
//TODO:在此处添加更新逻辑
更新(游戏时间);
}
/// 
///这就是所谓的比赛应该平局的时候。
/// 
///提供计时值的快照。
受保护覆盖无效绘制(游戏时间游戏时间)
{
图形设备。清晰(颜色:矢车菊蓝);
DateTime nowDatetime=DateTime.Now;
//TODO:在此处添加图形代码
基础。抽签(游戏时间);
}
}
}

您正在使用非静态方法初始化
nowString
。这将是编译器错误。

要使其正常工作,您必须将
nowDateTime
声明为
静态

static DateTime nowDateTime = DateTime.Now;
string nowString = nowDateTime.ToString();

您可以将初始化代码移动到构造函数中,使其对实例字段有效:

public class Game1 : Microsoft.Xna.Framework.Game
{
    SpriteFont font;
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    DateTime nowDateTime;
    string nowString;

    public Game1()
    {
        nowDateTime = DateTime.Now;
        nowString = nowDateTime.ToString();
    }
}

你所说的
这本书中的代码起作用是什么意思?
-你让它起作用了吗,还是你只是假设这本书的作者没有搞砸?
string nowString=nowDateTime.ToString()这是不允许的。您无法访问非静态成员。你确定第一个示例是编译的吗,因为它应该是我的第一个可以工作并且编译得很好这就是为什么我对自己的代码不工作感到困惑的原因--通过查看第一个示例中的缩进,我猜部分(甚至全部)代码在一个方法中,你没有把它复制粘贴到你的文章中。这是在第一个代码块末尾的一个神奇的反勾号。唯一可能的解释!问题是,当我从书(我下载的)中获取代码时,它运行良好,并且可以编译,但当我自己编写代码时,它会给出错误….@Jannikhueserpetersen请阅读
public class Game1 : Microsoft.Xna.Framework.Game
{
    SpriteFont font;
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    DateTime nowDateTime;
    string nowString;

    public Game1()
    {
        nowDateTime = DateTime.Now;
        nowString = nowDateTime.ToString();
    }
}