【问题标题】:foreach statement cannot operate?foreach 语句不能运行?
【发布时间】:2018-10-11 05:56:58
【问题描述】:
var maxHeight = draw._shapes.Aggregate((agg, next) =>next.height > agg.height ? next : agg);
if (draw._shapes.Count == 0)
    trackBar_Size.Maximum = 484;
else
{
    foreach (float heights in maxHeight)
    {
        if (heights < 412)
        {
            trackBar_Size.Maximum = 484;
        }
        else if (heights > 412)
        {
            trackBar_Size.Maximum = 415;
        }
    }
}

错误 3 foreach 语句无法对“sCreator.Shape”类型的变量进行操作,因为“sCreator.Shape”不包含“GetEnumerator”的公共定义

我在 var maxHeight 语句中收到此错误。那么如何修复此错误并将 LINQ 结果用作浮点值?

【问题讨论】:

标签: c# linq


【解决方案1】:

那是因为Aggregate 方法返回单个值(据我所知,_shapes 中的最大值)。

简单地说,试着写maxHeight.GetEnumerator() 看看,那个编译器会抱怨。为了使用foreach 循环,您需要有集合(有迭代器)。

或者,尝试写maxHeight.GetType()(或maxHeight.ToString())来检查它到底是什么。

或者只是在调试模式下检查变量,在适当的地方设置断点。

【讨论】:

    【解决方案2】:
    var maxHeight = draw._shapes.Aggregate((agg, next) => next.height > agg.height ? next : agg);
                if (maxHeight.height > 412)
                {
                    trackBar_Size.Maximum = 412;
                }
                else if (maxHeight.height < 412)
                {
                    trackBar_Size.Maximum = 484;
                }
    

    此代码将获得您想要的高度作为浮点值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多