提问人:TheMostEpic 提问时间:10/28/2019 更新时间:10/28/2019 访问量:125
在 C# 中通过索引号调用类中所有实例的属性?
Calling property of all instances in class by an index number in C#?
问:
在 C# 中,是否可以从一个类创建多个对象并通过索引号引用每个实例?
这是我尝试执行的操作的示例:
public class movie
{
public string name;
}
class Program
{
static void Main(string[] args)
{
movie[] myMovie = new movie[3];
myMovie[0].name = "Harry Potter";
myMovie[1].name = "Lord of The Rings";
myMovie[2].name = "Star Wars";
for (int i = 0; i < 3; i++)
{
Console.WriteLine(myMovie[i].name);
}
}
}
答:
5赞
canton7
10/28/2019
#1
你快到了。
当您这样做时,您正确地创建了一个由 3 个元素组成的数组,但默认情况下,这些元素中的每一个都是。这意味着如果你尝试这样做,你会得到一个,例如。movie[] myMovie = new movie[3]
movie
null
NullReferenceException
myMovie[0].name = "..."
您需要实例化三个单独的实例,并将它们分配给数组中的相应元素。您可以手动执行此操作:movie
movie[] myMovie = new movie[3];
myMovie[0] = new movie();
myMovie[1] = new movie();
myMovie[2] = new movie();
但是,循环是一种更简单的方法:for
movie[] myMovie = new movie[3];
for (int i = 0; i < movie.Length; i++)
{
myMovie[i] = new movie();
}
或者,您可以实例化实例,为它们命名,然后将它们一次性添加到您的数组中,如下所示:movie
movie[] myMovie = new movie[]
{
new movie()
{
name = "Harry Potter",
},
new movie()
{
name = "Lord of the Rings",
},
new movie()
{
name = "Star Wars",
}
};
5赞
Dmitry Bychenko
10/28/2019
#2
是的,您可以拥有实例的集合;在您的情况下,它可以是:List<movie>
static void Main(string[] args)
{
// Collection of movies (empty)
List<movie> myMovie = new List<movie>();
// Let's add some movies into the collection
myMovie.Add(new movie() {name = "Harry Potter"});
myMovie.Add(new movie() {name = "Lord of The Rings"});
myMovie.Add(new movie() {name = "Star Wars"});
// Time to inspect the collection
Console.WriteLine($"We have {myMovie.Count} movies in the collection");
Console.WriteLine("They are:");
// myMovie[i] returns i-th movie within the collection
for (int i = 0; i < myMovie.Count; ++i)
Console.WriteLine($" {i + 1}. {myMovie[i].name}");
}
评论
0赞
TheMostEpic
10/28/2019
我得到了工作对象列表。谢谢!
评论
movie