c#对象在当前上下文中不存在

标签 c# constructor

免责声明:我是 C# 新手。我很可能做错了什么,但我不知道要尝试Google什么,所以我希望有人能告诉我我做错了什么.

无论如何,我在 createPlayer 方法中使用我的构造函数创建了一个播放器对象,我可以打印创建的对象的值,但是之后我不能再打印它了,它说:

player1 doesn't exist in the current context.

我该怎么办?

主文件

using System;

namespace project
{
    class Program
    {
        static void Main(string[] args)
        {
                createPlayer();

            Console.WriteLine(player1.Name); //Doesn't exist in current context
            Console.ReadKey();
        }
        static public void createPlayer()
        {
            Console.WriteLine("\nType in your name :");
            Player player1 = new Player(Console.ReadLine()); 
            Console.WriteLine("\n Name: " + player1.Name + "\n Speed: " + player1.Speed + "\n Defence: " + player1.Defence + "\n Damage: " + player1.Damage);
            Console.WriteLine("\nPress 1 to continue, Press 2 to reroll.");
        }
    }
}

构造函数

 using System;

using System.Collections.Generic;
using System.Text;

namespace projekti
{
    public class Player
    {
        public string Name;
        public int Speed;
        public int Damage;
        public int Defence;
        public int Health;
        public Player(string nm)
        {
            Name = nm;
            Random r = new Random();
            Speed = r.Next(1, 26);
            Damage = r.Next(1, 26);
            Defence = r.Next(1, 26);
            Health = 100;
        }
    }
}

最佳答案

player1createPlayer() 中实例化,因此在该函数的本地范围内。如果你想让其他函数访问它,你可以让 createPlayer() 返回 player1

static void Main(string[] args)
{
    var player1 = createPlayer();

    Console.WriteLine(player1.Name);
    Console.ReadKey();
}
static public Player createPlayer()
{
    Console.WriteLine("\nType in your name :");
    Player player1 = new Player(Console.ReadLine()); 
    Console.WriteLine("\n Name: " + player1.Name + "\n Speed: " + player1.Speed + "\n Defence: " + player1.Defence + "\n Damage: " + player1.Damage);
    Console.WriteLine("\nPress 1 to continue, Press 2 to reroll.");

    return player1;
}

关于c#对象在当前上下文中不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48364062/

相关文章:

c# - Newtonsoft JSON重命名属性名称取决于另一个属性

c# - 在 Linq-To-Sql 中避免 "Nullable object must have a value."

c# - 之前声明所有局部变量是否有性能提升或其他原因?

c++ - 递归复制构造函数?

C# 使用 Newtonsoft.Json 将 JSON 字符串反序列化为对象

c# - C# 任务和全局变量

ios - Swift 不识别这个特定的 Objective-C 类构造函数

java - 如何从枚举构造函数中抛出异常?

c++ - 构造函数中的初始化列表可以在模板类中使用吗?

c# - 自定义属性的构造函数何时运行?