gpt4 book ai didi

c# - 如何将静态数组的元素传递给非静态方法?

转载 作者:太空宇宙 更新时间:2023-11-03 19:17:25 25 4
gpt4 key购买 nike

我有一个静态数组,我需要将它的任意元素传递给一个非静态方法。

我该怎么做?

public class MyClass
{
public static int[] staticArray = { 3, 11, 43, 683, 2731 };

public void SomeMethod(int value)
{
//...stuff...
}

public static void staticMethod()
{
SomeMethod(staticArray[2]); //error here
}
}

当我尝试类似的操作时,出现错误 An object reference is required for the non-static field, method, or property

最佳答案

您的代码没有问题,但是当您尝试调用 instance 方法,或者访问类实例以外的非静态字段/属性,比如从静态方法。例如:

class MyClass
{
private int imNotStatic;

public static void Bar()
{
// This will give you your 'An object reference is required` compile
// error, since you are trying to call the instance method SomeMethod
// from a static method, as there is no 'this' to call SomeMethod on.
SomeMethod(5);

// This will also give you that error, as you are calling SomeMethod as
// if it were a static method.
MyClass.SomeMethod(42);

// Again, same error, there is no 'this' to read imNotStatic from.
imNotStatic = -1;
}

public void SomeMethod(int x)
{
// Stuff
}
}

确保您没有执行上述任一操作。您确定要从构造函数调用 SomeMethod 吗?

关于c# - 如何将静态数组的元素传递给非静态方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15175741/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com