如何将一个类中生成的变量转换为另一个类?

时间:2016-10-03 08:43:27

标签: c# arrays

我曾尝试使用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_1M_array_2等?通常我会使用inheritance

从另一个类调用一个varibel
Class_example CE = new Class_example();

Composition

public class wheel{}
public class car : wheel{}

1 个答案:

答案 0 :(得分:-1)

使您的字典保持静态并可从其他类访问?

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])}");
       }
    }
}