如何将一个类中生成的变量转换为另一个类
本文关键字:变量 转换 另一个 一个 | 更新日期: 2023-09-27 18:11:19
我曾尝试使用Inheritance
,但它没有开始工作,此外,我尝试使用Composition
,但同样很少成功。单个数组是从文本文件中读取的,这使其成为特定的数据。代码如下:
The generating code:
public static void ReadText(string[] args)
{
Dictionary<string, int[]> rows = new Dictionary<string, int[]>();
string[] lines = File.ReadAllLines("txt.txt");
int counter = 0;
foreach (string s in lines)
{
//Console.WriteLine(s);
string[] arr = s.Split(' ');
int[] array = new int[arr.Length];
for (int i = 0; i < arr.Length; i++)
{
array[i] = Convert.ToInt32(arr[i]);
}
string key = "M_array_" + counter++;
rows.Add(key, array);
//ShowArray(array);
}
foreach (string key in rows.Keys)
{
Console.WriteLine($"{key}: {String.Join(" ", rows[key])}");
}
Console.ReadLine();
}
我如何调用M_array_1
, M_array_2
等在其他类?通常我从另一个类调用一个变量,我使用inheritance
:
Class_example CE = new Class_example();
或Composition
:
public class wheel{}
public class car : wheel{}
使您的字典静态并可从其他类访问?
public class MyClass
{
public static Dictionary<string, int[]> Rows = new Dictionary<string, int[]>(); // initialize just in case
public static void ReadText(string[] args)
{
Rows = new Dictionary<string, int[]>();
string[] lines = File.ReadAllLines("txt.txt");
...
}
}
public class AnotherClass
{
public void DoSomething()
{
// Make sure you have done MyClass.ReadText(args) beforehands
// then you can call the int array
int[] m_array_1 = MyClass.Rows["M_array_1"];
int[] m_array_2 = MyClass.Rows["M_array_2"];
// or
foreach (string key in MyClass.Rows.Keys)
{
Console.WriteLine($"{key}: {String.Join(" ", rows[key])}");
}
}
}