C#中如何在独立类中读取另一类的数组数据?
如何在C#中跨类访问另一个类的数组数据
我来帮你解决这个跨类读取数组的问题~首先得指出你当前代码的核心问题:你定义的monsterCards是CardInfo方法里的局部变量,它的作用域只限于这个方法内部,所以其他类根本没法访问到它。要实现跨类读取,我们需要调整这个数组的作用域,下面给你两种常用的解决方案:
方案1:将数组改为类的静态公共成员(简单直接)
把数组从方法内部移到类的级别,定义成静态公共只读属性,这样其他类就能直接通过类名访问它,同时还能防止外部意外修改原数据。
修改后的GameInfo类代码:
using System; using static System.Console; namespace Munchkin { class GameInfo { // 把数组定义为类的静态公共只读属性 public static string[,] MonsterCards { get; } = new string[,] { { "Bob", "500" }, { "Billy", "600" }, { "Joe", "700" }, { "Frank", "750" }, { "BillyBob", "850" } }; public static void CardInfo() { // 类内部可以直接使用这个数组 for (int i = 0; i < MonsterCards.GetLength(0); i++) { WriteLine($"Monster name {MonsterCards[i, 0]}, Health Points {MonsterCards[i, 1]}"); } } } }
然后在其他类中访问的示例:
namespace Munchkin { class YourOtherClass { public void ReadMonsterData() { // 通过类名直接访问静态数组 string[,] monsterData = GameInfo.MonsterCards; // 遍历输出示例 for (int i = 0; i < monsterData.GetLength(0); i++) { Console.WriteLine($"怪物名称:{monsterData[i,0]},生命值:{monsterData[i,1]}"); } } } }
方案2:通过公共方法返回数组(更符合封装原则)
如果不想直接暴露数组(避免外部代码意外修改原数组),可以把数组设为类的私有静态字段,然后提供一个公共方法来返回数组的副本(或者原数组,根据你的需求)。
修改后的GameInfo类代码:
using System; using static System.Console; namespace Munchkin { class GameInfo { // 私有静态字段,仅类内部可访问 private static string[,] _monsterCards = new string[,] { { "Bob", "500" }, { "Billy", "600" }, { "Joe", "700" }, { "Frank", "750" }, { "BillyBob", "850" } }; public static void CardInfo() { for (int i = 0; i < _monsterCards.GetLength(0); i++) { WriteLine($"Monster name {_monsterCards[i, 0]}, Health Points {_monsterCards[i, 1]}"); } } // 公共方法,返回数组副本(保护原数据不被外部修改) public static string[,] GetMonsterCards() { string[,] cardCopy = new string[_monsterCards.GetLength(0), _monsterCards.GetLength(1)]; Array.Copy(_monsterCards, cardCopy, _monsterCards.Length); return cardCopy; } } }
其他类中的调用示例:
namespace Munchkin { class YourOtherClass { public void ReadMonsterData() { // 调用方法获取数组副本 string[,] monsterData = GameInfo.GetMonsterCards(); // 后续操作和方案1一致 for (int i = 0; i < monsterData.GetLength(0); i++) { Console.WriteLine($"怪物名称:{monsterData[i,0]},生命值:{monsterData[i,1]}"); } } } }
小提示
如果你的数组内容不会发生变化,推荐用方案1的只读属性,既简洁又安全;如果需要控制数组的访问逻辑(比如后续要加权限验证、缓存等),方案2的方法调用会更灵活。
内容的提问来源于stack exchange,提问作者Colton Slayden
相关产品推荐
相关产品推荐

