所以我有一个自定义类(即MyClass),然后我用它来声明一个数组。如何将“.Count”属性添加到我的自定义类以获取数组的大小?
谢谢。
static void Main()
{
MyClass[] test = new MyClass[2];
test[0].str = "Hello";
test[1].str = "World";
Console.WriteLine("Count : " + test.Count);
}
class MyClass
{
public string str;
}
答案 0 :(得分:2)
你已经创建了一个数组,所以它应该已经有了一个test.Length属性。
答案 1 :(得分:1)
您的自定义类不知道它在数组中。因此,您无法计算数组中对象的数量,因为只有Main()知道该数组包含多少个对象。
答案 2 :(得分:0)
首先你的代码应该是
MyClass[] test = new MyClass()[2];
第二,如果您想知道已经生成了多少个类的实例。创建一个
public static int Count;
并在类的构造函数中增加其属性,如
public MyClass()
{
Count++;
}
如果你想知道实例的数量,那就写一下
MessageBox.Show(Myclass.Count.ToString());