【UNITY】报错6【CS1519】 Invalid toke ‘foreach‘ in class, record, struct, or interface member declaration

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FunctionEx3 : MonoBehaviour
{
    public GameObject[] gameObjectToAlign;
    float sunX = 0;
    foreach (GameObject go in gameObjectToAlign)
        {
            sunX += go.transform.position.x;
        }

void Start(){}

报错:error CS1519:Invalid t.o.k.e.n ‘foreach’ in class, record, struct, or interface member declaration

ai的解释:This error message is usually seen in C# programming language and it indicates that the keyword “foreach” has been used inappropriately within a class, record, struct or interface declaration.
The “foreach” keyword is used to iterate over collections or arrays, and it can only be used within method bodies, property getters, or lambda expressions.
To resolve this error, make sure that the “foreach” keyword is used within the appropriate context. If you are trying to iterate over a collection within a class, record, struct or interface declaration, move the “foreach” loop to a method body or property getter.

它表示关键字"foreach"在类,记录,结构或接口声明中被错误地使用。
"foreach"关键字用于在集合或数组中进行迭代,它只能在方法主体,属性getter或lambda表达式中使用。如果在类,记录,结构或接口声明中使用“foreach”关键字,就会引发此错误。
要解决此错误,请确保在适当的上下文中使用“foreach”关键字。如果您想在类,记录,结构或接口声明中迭代集合,则需要将“foreach”循环移至方法主体或属性getter中。

要在类,记录,结构或接口中实现迭代的功能,可以使用IEnumerator和IEnumerable接口。在类中实现这两个接口可以使其与foreach语法相容。

参考
好像JAVA中的循环不可以直接写在方法体外

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值