【问题标题】:Can't access a property of an object if it's in an array如果对象在数组中,则无法访问该对象的属性
【发布时间】:2022-01-16 14:57:52
【问题描述】:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public struct Test {
    public string testString { get; set; }
    public Test(string TestString) {
        testString = TestString;

    }

}

public class arrayTest : MonoBehaviour {
    void Start() {
        object[] array = new object[2];
        Test tester = new Test("hello");
        array[0] = tester;
        Debug.Log(array[0].testString);

    }

}

我对 C# 很陌生,如果这是一个愚蠢的问题,我很抱歉。这只是我的主程序的简化版本,但我不断收到相同的错误,即

“object”不包含“testString”的定义,并且找不到接受“object”类型的第一个参数的可访问扩展方法“testString”(您是否缺少 using 指令或程序集引用? )

如果对象不在数组中,它工作正常,但一旦它给了我这个。我也尝试过使用 TestString 但无济于事。任何帮助将不胜感激。

【问题讨论】:

  • 你为什么使用object[](c#中几乎所有东西的母类型)而不是实际类型Test[]

标签: c# arrays unity3d object


【解决方案1】:

你的问题就在这里;

object[] array = new object[2];

一旦进入该数组,您的 Test 对象就会被隐式转换为“普通”对象,因此您只能对任何普通对象执行操作。

如果您想要一个 Test 对象数组,请改为这样做;

Test[] array = new Test[2];

或者更简洁,

var array = new Test[2];

【讨论】:

    【解决方案2】:

    您必须将对象类转换为测试器的测试结构,因为数组是一个对象类并且没有 testString 属性

     Debug.Log( ((Test) array[0]).testString );
    

    如果您不需要使用任何其他类,也可以这样定义数组

     Test[] array = new Test[2];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-26
      • 2011-07-05
      • 2021-08-23
      • 2017-09-04
      • 2020-05-04
      相关资源
      最近更新 更多