繁体   English   中英

将Count属性添加到C#中的自定义类

[英]Add a Count property to custom class in C#

因此,我有一个自定义类(即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;
}

您已经制作了一个数组,因此它应该已经具有一个test.Length属性。

您的自定义类不知道它在数组中。 因此,由于只有Main()知道数组包含多少个对象,因此您无法获得数组中对象的数量的计数。

首先你的代码应该像

MyClass[] test = new MyClass()[2];

第二,如果您想知道已经生成了多少个类实例。 创建一个

public static int Count;

并在类的构造函数中增加其属性,例如

public MyClass()
{
    Count++;
}

如果您想知道实例数,则只需编写

MessageBox.Show(Myclass.Count.ToString());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM