繁体   English   中英

C#Class public int无法引用非静态int

[英]C# Class public int cannot reference the non-static int

我遇到了一个小问题,(我环顾四周可以对这样的东西进行罚款,但没有帮助),如果我创建了int size = 1; 然后具有一个公共int backgroundWidth = size * Images.Background.Width; 当它是static int时此方法有效,但我想随意更改int。 这都在同一个类中,应该可以工作,但是它不喜欢乘ints吗?

编辑:10: 21 12/3/2013

@dcastro我尝试使用给我的格式,但是仍然存在一个小问题。

因为我使用的是XNA,而且格式可能有一些偏差,所以这里是更独立的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace **.StartUp
{
    public class Resize
    {
        #region Define
        private int size = 1;
        //
        public int backgroundWidth;
        public int backgroundHeight;
        #endregion

        #region Update
        public static void Update(GameTime gameTime)
        {
        }
        #endregion

        #region public Methods
        #endregion
    }
}

我已经定义了int,但是当我添加代码的下半部分时,它需要一个返回值才能起作用。 否则我可能会使其复杂化。

我将其添加到公共方法中:

public MyClass()
    {
        backgroundWidth = size * Images.Background.Width;
    }

编辑: 10 : 35 12/3/2013

现在的错误是该方法需要具有返回类型,并且不知道该怎么做。 我正在学习尽可能多的知识,现在正在复活我必须做的事情。 如果可以的话,我想获得一些帮助,谢谢。

编辑: 10 : 26 12/4/2013

现在,我已经可以调用图像了,但是使用一种不同的方法,我仍然使用Resize类,但只构造它们,然后在主类( Game1.cs )中使用它们。 我添加了一个布尔值,以便在有人想要更改大小时都会通过if语句并更改整数。

Game1.cs (更新方法):

protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            #region GameState Switch
            switch (gameState)
            {
                case GameStates.StartUp:
                    break;
                case GameStates.TitleScreen:
                    StartUp.TitleScreen.Update(gameTime);
                    break;
                case GameStates.Options:
                    break;
                case GameStates.Credits:
                    break;
            }
            #endregion

            #region Image Resize
            if (resize.change == true)
            {
                resize.change = false;
                resize.continueHeight = resize.size * StartUp.Images.Continue.Height;
                resize.continueWidth = resize.size * StartUp.Images.Continue.Width;
                StartUp.TitleScreen.con = new Rectangle(330, 246, resize.continueWidth, resize.continueHeight);
            }
            #endregion

            base.Update(gameTime);
        }

您必须在构造函数中初始化该字段。

public class MyClass
{
    private int _size = 1;
    private int _backgroundWidth;

    public MyClass()
    {
        //TODO: initialize 'Images'
        _backgroundWidth = _size * Images.Background.Width;
    }
}

根据MSDN文档

实例字段的变量初始化器无法引用正在创建的实例。

这意味着你不能做这样的事情:

private int _backgroundWidth = this._size * this._something;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM