类类型的访问类型

时间:2015-06-14 21:33:49

标签: c#

当我去声明一个Character类型的变量时,访问类型为public,它给出了错误“Unexpected symbol,public”。

public static void Main (string[] args)
{
    public Character player = new Character();
    Map map = new Map();
    ReciveInput();
}

角色等级

using System.Collections.Generic;
using System;

namespace SimpleTextAdventure
{
    public class Character
    {
        public Character ()
        {
            List<string> items = new List<string>();
            public Vector location = new Vector(2,2);
        }
    }
}

删除公共修复错误然后,据我所知,将给它默认类型内部,这不是我想要的。错误的原因是什么?

1 个答案:

答案 0 :(得分:0)

您只能将public用于字段,而不能用于本地变量:

public class SomeClass
{
    public Character player1 = new Character(); // this will compile

    public void SomeMethod()
    {
        public Character player2 = new Character(); // this won't compile
    }
}

public删除player1确实会使其成为内部版本。但是,相同的可见性规则不适用于方法中定义的局部变量。它们既不是public也不是internal;它们是该方法的私有方式,只有在执行方法时才存在,除非在闭包的专业情况下。

假设您希望player可用于代码的其他部分,您需要做的是从Main中删除声明,而是将以下内容添加到其类中:< / p>

public static Character player = new Character();

请注意,虽然这样的全局变量是非常糟糕的做法。你最好在Main中创建它,然后在通过构造函数创建它们时将它传递给其他类。例如,如果Map需要了解角色的位置,因此需要访问player,您可以将代码更改为:

public static void Main (string[] args)
{
    Character player = new Character();
    Map map = new Map(player);
    ReciveInput();
}

public class Map
{
    private readonly Character _player;

    public Map(Character player)
    {
        _player = player;
    }

    public SomeMethod
    {
        // access the character using _player here
    }
}
相关问题