【问题标题】:Accessing an instance object within an instance object在实例对象中访问实例对象
【发布时间】:2015-08-20 15:41:28
【问题描述】:

对于 C# 来说非常陌生,并试图从 .tsv 文件创建一个简单的清单

我有一个脚本(文本解析器),它读取文件,创建一个名为“TableData”的对象实例并将所有数据传输到该实例。

文本解析器的相关部分如下所示:

public class TextParser : MonoBehaviour {
...
...

            line = reader.ReadLine();
            string[] tableKey = line.Split('\t');

            line = reader.ReadLine();
            string[] typeKey = line.Split('\t');

            line = reader.ReadLine();
            string[] entries = line.Split('\t');

            TableData tableData = new TableData(tableKey,typeKey,entries);
...
...

*稍后在脚本中我有一个循环,将每个附加行添加到该实例的列表中

TableData 脚本只有 3 个字段:2 个字符串数组和 1 个字符串数组列表:

public class TableData : MonoBehaviour
{
    public string[] tableKey;
    public string[] tableType;
    public List<string[]> excelData = new List<string[]>();


    public TableData(string[] _tableKey, string[] _tableType, string[] entries)
    {
        tableKey = _tableKey;
        tableType = _tableType;

        excelData.Add (entries);
    }
}

所以问题是,如果我实例化“TextParser”类的一个对象(在运行时),然后它又实例化一个“TableData”类的对象 - 我如何访问“tableData”实例中的数据?

【问题讨论】:

  • tableData.excelData ?

标签: c# unity3d instance inventory


【解决方案1】:

试试这样的

    public class TableData : MonoBehaviour
    {
        public string[] tableKey;
        public string[] tableType;
        public DataTable dt = new DataTable();

        public TableData()
        {
            dt.Columns.Add("Key", typeof(string));
            dt.Columns.Add("Type", typeof(string));
            dt.Columns.Add("Entry", typeof(string));
        }


        public TableData(string[] _tableKey, string[] _tableType, string[] entries)
        {

            for (int i = 0; i < _tableKey.Length; i++)
            {
                dt.Rows.Add(new object[] { _tableKey[i], _tableType[i], entries[i] });
            }

        }
    }
​

【讨论】:

    【解决方案2】:

    公开,并在class 范围内

    public class TextParser : MonoBehaviour {
        //...
        public TableData tableData;
        //...
    }
    

    那你就做

    TextParser tp;
    TableData tableData = tp.tableData;
    // Do something
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-14
      • 2014-12-22
      • 2018-02-18
      • 2011-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多