【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中的循环不可以直接写在方法体外

猜你喜欢

转载自blog.csdn.net/qq_50653422/article/details/129782366
今日推荐