不能在同一个类中使用声明的字典?

时间:2012-12-24 23:11:05

标签: c#

好的,我无法弄清楚到底发生了什么。

我宣布并初步化了一本字典:

public Dictionary<byte, Color> blobType = new Dictionary<byte, Color>();

但是我不能在课堂上使用它,intelliscence也不会显示它。如果我尝试使用它,我会收到错误:

blobType.add(1, Color.White);

或者,如果我没有初始化它并尝试稍后:

    public Dictionary<byte, Color> blobType;
    blobType = new Dictionary<byte, Color>();

仍然无法使用它,就像它没有看到它在那里的blobType一样。

我尝试重命名变量,在VS2012中执行,仍然会发生同样的事情。因此,当类是另一个类中的对象时,它可以在类外部访问它。但VS2010 C#Express拒绝承认它在我宣布的类中存在。发生了什么事?

根据要求,全班:

namespace blob
{
    class Blob
    {
        public Texture2D texture;

        public Dictionary<byte, Color> blobType = new Dictionary<byte, Color>();
        blobType.add(1, Color.White);

        public Vector2 position;

        private float scale = 1;
        public float Scale
        {
            get { return scale; }
            set { scale = value; }
        }

        public Blob(Texture2D texture, float scale)
        {
            this.texture = texture;
            this.Scale = scale;
        }

        public void Draw(SpriteBatch spriteBatch)
        {
            spriteBatch.Draw(texture, position, null, Color.White, 0, Vector2.Zero, Scale, SpriteEffects.None, 0);
        }
    }
}

EDIT2:大写添加,同样的事情。 错误:

Error   1   Invalid token '(' in class, struct, or interface member declaration C:\Users\Iurie\Documents\Visual Studio 2010\Projects\blob\blob\blob\Blob.cs 20  21  blob

Error   2   Invalid token ')' in class, struct, or interface member declaration C:\Users\Iurie\Documents\Visual Studio 2010\Projects\blob\blob\blob\Blob.cs 20  36  blob

Error   3   'blob.Blob.blobType' is a 'field' but is used like a 'type' C:\Users\Iurie\Documents\Visual Studio 2010\Projects\blob\blob\blob\Blob.cs 20  9   blob

Error   4   'Microsoft.Xna.Framework.Color.White' is a 'property' but is used like a 'type' C:\Users\Iurie\Documents\Visual Studio 2010\Projects\blob\blob\blob\Blob.cs 20  31  blob

3 个答案:

答案 0 :(得分:8)

您不能在C#中的方法之外执行代码。要在字典中添加一组默认条目,请将它们添加到Blob类的构造函数中。

答案 1 :(得分:2)

您无法在方法之外执行代码。要添加默认值,请在构造函数中调用add。

class Blob
{
    public Texture2D texture;

    public Dictionary<byte, Color> blobType = new Dictionary<byte, Color>();

    public Blob() 
    {
        blobType.add(1, Color.White);
    }
}

答案 2 :(得分:0)

这将满足您的需求:

class Blob
{
    public Texture2D texture;

    public Dictionary<byte, Color> blobType = new Dictionary<byte, Color>() { { 1, Color.White } };

    public Vector2 position;

    private float scale = 1;
    public float Scale
    {
        get { return scale; }
        set { scale = value; }
    }

    public Blob(Texture2D texture, float scale)
    {
        this.texture = texture;
        this.Scale = scale;
    }

    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(texture, position, null, Color.White, 0, Vector2.Zero, Scale, SpriteEffects.None, 0);
    }
}