对集合中特定类型的对象进行计数,并将其用作文本框中的字符串

本文关键字:字符串 作文本 集合 类型 对象 | 更新日期: 2023-09-27 18:12:38

我想用集合中某一类图形的计数+1填充一个文本框。集合是图的泛型列表,图是图的某一类型的实例。

以下作品:

txtName.Text = figures.OfType<Square>().Count().ToString();

,但下面没有

txtName.Text = figures.OfType<figure.GetType()>().Count().ToString();

我得到错误"operator '>'不能应用于'method group'和'System.Type'类型的操作数"。

对集合中特定类型的对象进行计数,并将其用作文本框中的字符串

泛型类型参数需要在编译时指定,但是GetType()是一个在运行时调用的函数,所以这根本不起作用。错误信息表明编译器试图将您的代码解释为figures.OfType < figure.GetType() ...,这没有多大意义。

你可以这样做:

// Count figures whose type is exactly equal to the type of figure
txtName.Text = figures.Count(x => figure.GetType() == x.GetType()).ToString();
// Count figures whose type is equal to or a subtype of the type of figure
txtName.Text = figures.Count(x => figure.GetType().IsAssignableFrom(x.GetType())).ToString();