访问数组中的对象属性

时间:2015-05-20 19:41:13

标签: c# arrays object

class Program{

    static void Main(string[] args){

        object[] array = new object[1];

        CreateItem item = new CreateItem();
        item.name = "Necklace";
        item.value = 5;
        array[0] = item;

        Console.WriteLine(array[0].name); //This part of the code doesn't work. 
                                          //It can't find the property name. 
        Console.ReadLine();
    }
}

public class CreateItem {
    public string name;
    public int value;
}
你好!首先,我想说我对对象不是很熟悉,所以请原谅你在代码中看到的任何错误(尽管可以随意纠正它们,但这是一种很好的学习方式)。

我一直在使用C#制作小游戏,但我遇到了一个问题:当我将它们放入数组时,我无法访问我的对象属性。有没有人知道我应该使用哪些代码来访问我们在数组中的对象属性?

感谢阅读,再一次,原谅我所犯的任何愚蠢的错误,我对使用对象相当陌生。

4 个答案:

答案 0 :(得分:6)

如果您拥有一个您感兴趣的强类型(并且您已经知道该类型),则不应该使用对象数组。

CreateItem[] array = new CreateItem[1];

CreateItem item = new CreateItem();
item.name = "Necklace";
item.value = 5;
array[0] = item;

Console.WriteLine(array[0].name);

现在将按预期输出项链。

答案 1 :(得分:2)

你应该考虑使用泛型和列表,这是一个非常普遍和有价值的概念,正如Generics解决的拳击和拆箱概念一样。

class Program{

  static void Main(string[] args){

    List<CreateItem> list  = new List<CreateItem>();

    CreateItem item = new CreateItem();
    item.name = "Necklace";
    item.value = 5;
    list.Add( item );

    Console.WriteLine(list[0].name); //This part of the code doesn't work. 
                                      //It can't find the property name. 
    Console.ReadLine();
  }


}

答案 2 :(得分:1)

您可以将对象强制转换为您的类型,即: Console.WriteLine(((CreateItem)array[0]).name);

或(更有效)

将您的array定义为CreateItem[] array = new CreateItem[1];

答案 3 :(得分:0)

<a href="DisciplineDrawings/Compliance/cadfiles/compliance-ada-03.html" class="btn btn-primary block-center hidden-xs hidden-sm ">CAD</a>

创建一个类型为Object的元素数组,它是.NET中所有其他类的基类。

当你这样做时:

object[] array = new object[1];

发生了对基本类型的隐式转换,通过array[n] = item; ,您只能访问array[n]对象的Object类型部分的成员(例如CreateItem或{{ 1}} - 将调用它们的覆盖)。

如果要访问整个ToString()对象,则必须使用强制转换运算符将基类型的引用转换回原始类型,例如:

GetType()

这种显式转换容易出错,具有运行时开销,这是设计不佳的标志。如果您事先知道集合的类型,请按照其他答案建议声明该类型的集合:

CreateItem