C#:非静态字段、方法或属性需要对象引用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12999919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:16:56  来源:igfitidea点击:

C#: An object reference is required for the non-static field, method, or Property

c#objectmethodsreference

提问by Charles Han

I feel bad for asking this when there are so many questions that are related but I was not able to find/understand the answer I am looking for.

当有这么多相关的问题但我无法找到/理解我正在寻找的答案时,我为问这个感到难过。

// 2. Develop a program to convert currency X to currency Y and visa versa.

// 2. 开发一个程序将货币 X 转换为货币 Y,反之亦然。

using System;

class Problem2
{
    static void Main (string[] args)
    {
        while (true) {
            Console.WriteLine ("1. Currency Conversion from CAD to Won");
            Console.WriteLine ("2. Currency Conversion from Won to Cad");
            Console.Write ("Choose from the Following: (1 or 2)? ");
            int option = int.Parse( Console.ReadLine() );
            //double x;
            if (option == 1) {
                Console.WriteLine ("Type in the amount you would like to Convert CAD to Won: ");
                //double y =double.Parse( Console.ReadLine());
                //Console.WriteLine( cadToWon( y ) );
                Console.WriteLine( cadToWon( double.Parse( Console.ReadLine() ) ));
            }
            if (option == 2) {
                Console.WriteLine ("Type in the amount you would like to Convert Won to CAD: ");
                Console.WriteLine( wonToCad (double.Parse( Console.ReadLine())));
            }
        }
    }

    double cadToWon( double x )
    {
        return x * 1113.26;
    }

    double wonToCad( double x)
    {
        return x / 1113.26;
    }
}

This give me the Error messgae "An object reference is required for the non-static field, method, or property 'Problem2..." I know that I'll be able to run the program if I add static infront of the methods but I'm wondering why I need it (I think it's because Main is static?) and what do I need to change in order to use these methods without adding static to them?

这给了我错误消息“非静态字段、方法或属性 'Problem2 ... 需要对象引用...”我知道如果在方法前面添加静态,我将能够运行该程序,但是我想知道为什么我需要它(我认为这是因为 Main 是静态的?)以及我需要更改什么才能使用这些方法而不向它们添加静态?

Thank you

谢谢

采纳答案by Adam Rackis

Since your Main method is static, cadToWon and wonToCad alsohave to be static if you want to call them from Main.

由于您的 Main 方法是静态的,如果您想从 Main 调用它们,cadToWon 和 wonToCad必须是静态的。

static double cadToWon(double x) //...


static double wonToCad(double x) //...

The other option would be to break all of the logic of your Main, cadToWon, and wonToCad methods out into a new class, and then have you Main method simply set up and run that new class. But I suspect that might be beyond the scope of your assignment.

另一种选择是将 Main、cadToWon 和 wonToCad 方法的所有逻辑分解为一个新类,然后让 Main 方法简单地设置并运行该新类。但我怀疑这可能超出了你的任务范围。



To answer you question of whyadding static makes this work:

要回答您为什么添加静态使这项工作的问题:

staticmethods are sharedacross all instances of a class. So no matter what instance of class Problem2you're in, there's only oneMainmethod that's shared across all of them.

static方法在类的所有实例之间共享。因此,无论Problem2您在哪个类实例中,只有一种Main方法在所有实例之间共享。

cadToWon, however, is an instancemethod. It belongs to a particularinstance of class Problem2.

cadToWon然而,是一个实例方法。它属于class的特定实例Problem2

As a result, you can't call cadToWonfrom Main, since Maindoesn't know what instanceof Problem2to call cadToWonon. Maindoesn't know what instance to call cadToWonon since Maindoesn't belongto any instance.

其结果是,你不能叫cadToWonMain,因为Main不知道什么情况下Problem2调用cadToWon上。 Main不知道调用哪个实例,cadToWon因为Main不知道belong任何实例。

回答by LightStriker

It is because Main, being static, is not assigned to any instance of Problem2. Not knowing at which instance of Problem2 to send the variable, it is unable to call the right method.

这是因为 Main 是静态的,没有分配给 Problem2 的任何实例。不知道在 Problem2 的哪个实例发送变量,无法调用正确的方法。

Right now, your method doesn't modify any fields of any Problem2. But they could, and that's the whole problem. Which instance of Problem2 should they modify? The static method has no way to know that.

现在,您的方法不会修改任何 Problem2 的任何字段。但他们可以,这就是整个问题。他们应该修改 Problem2 的哪个实例?静态方法无法知道这一点。

So, if you had initialized an instance of Problem2, you could call its own version of the method from the static Main.

所以,如果你已经初始化了一个 Problem2 的实例,你可以从静态 Main 调用它自己的方法版本。

Problem2 problem = new Problem2();

problem.cadToWon(...)

回答by codingbiz

Making your methods staticwill solve that problem. You cannot call an instance member (not preceded with static) from a static method (e.g. static void main(..)). It either both of them have to be declared staticor you create the instance of the class in which the methods are and access them through the instance. I don't think you need that here

制定您的方法static将解决该问题。您不能static从静态方法(例如static void main(..))调用实例成员(不以 开头)。它要么必须声明它们,要么static创建方法所在的类的实例并通过实例访问它们。我认为你不需要这里

static double cadToWon( double x )
{
    return x * 1113.26;
}

static double wonToCad( double x)
{
    return x / 1113.26;
}

Accessing through instance

通过实例访问

Program2 p2 = new Program2();
double x = p2.wonToCad(10);

回答by Bogdan Alexandru

If you don't want to change them to static, then simply move them to another class, and then inside Main create an object and use the functions.

如果您不想将它们更改为静态,则只需将它们移动到另一个类,然后在 Main 创建一个对象并使用这些函数。

回答by Laurie Stearn

This solution is exactly the one sought here. Trying to pass an object from Static Main into a method in Class: Program is well nigh impossible without:

这个解决方案正是这里寻求的解决方案。尝试将对象从静态主传递到类中的方法:程序几乎不可能没有:

 `Program ProgramInstance = new Program();
 ProgramInstance.ProcessObject(MyObject);`