计算集合中某种类型的对象,并将其用作文本框中的字符串

我想用一个集合中的一个数字的count + 1填充一个文本框。 该集合是图的通用列表,图是某种类型的图的实例。

以下作品:

txtName.Text = figures.OfType().Count().ToString(); 

但以下情况并非如此

 txtName.Text = figures.OfType
().Count().ToString();

我得到错误“operator’>’不能应用于’方法组’和’System.Type’类型的操作数”。 我需要做些什么来完成这项工作?

需要在编译时指定generics类型参数,但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();