【问题标题】:How can I make this var be accessible by other classes?如何使其他类可以访问此 var?
【发布时间】:2020-12-12 09:52:00
【问题描述】:

所以我正在制作一个基于 SadConsole 库的简单游戏,当另一个类调用函数时,我想要重置这个 var 的位置。但我无法访问它。有什么办法解决吗?

using System;
using System.Collections.Generic;
using System.Text;
using SadConsole.Components;
using SadConsole;
using SadConsole.Themes;
using SadConsole.Controls;
using Console = SadConsole.Console;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace SAD
{
    class MainConsole: Console
    {
        
        public MainConsole() : base(80,25)
        {
            Random random = new Random();

            var console = new Console(80, 25);
            var Control = new ControlsConsole(80,25);
            Children.Add(Control);
            console.IsVisible = true;
            var button = new SadConsole.Controls.Button(10, 5) // THIS VAR. I WANT ITS POSITION TO BE RESET BUT I CAN ACCESS IT
            {
                Text = "Press",
                Position = new Point(5, 5),
                Theme = new ButtonLinesTheme()
            };
            button.Click += (s, a) => button.Position = new Point(random.Next(1, 81), random.Next(1,26));
            Control.Add(button);

           
        }
    }
}

【问题讨论】:

  • 使用 public 修饰符全局定义变量。
  • @user_mat 全局是什么意思? C# 中没有全局变量
  • @CamiloTerevinto 只是该库出于各种原因需要 Microsoft.Xna

标签: c# .net oop var


【解决方案1】:

与其在构造函​​数中声明变量,不如将其设为public——这将使它在你的程序集之外也可用——或internal——这将使它可用于同一类中的所有类程序集 -- 属性。

using foo;
...

namespace SAD {

    class MainConsole: Console
    {

        public SadConsole.Controls.Button TheButton {get; private set;}
        public MainConsole() : base(80,25) {
           ...
           TheButton = new SadConsole.Controls.Button(10,5) {...}
        }
    }
}

private setter 确保 TheButton 只能从 MainConsole 类中设置,但 getter 是 public 所以一旦设置了属性,您就可以从其他任何地方访问 TheButton在代码中,您有一个 MainConsole 类的实例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 2012-11-01
    相关资源
    最近更新 更多