error非静态字段,方法或属性需要对象引用 [英] error An object reference is required for the non-static field, method, or property

查看:121
本文介绍了error非静态字段,方法或属性需要对象引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

i learn c++ and i begin learn c#, i dont understand method
help me error







using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace text1
{
    class Program
    {
        public int pt(int l, int r)
        {
            return l + r;
        }
        static void Main(string[] args)
        {
            float i;
            var c = 10;
            Console.WriteLine("Hello World");
            Console.ReadLine();
            for (i = 1; i <= 10; i++)
                {   Console.WriteLine("Hello World");
                    Console.WriteLine(c);
                    
                };
            string a, b;
            a = "vu anh";
            b = "dep trai";
            Console.WriteLine(a + " " + b);
            int j;
            j = pt(3, 4);
            Console.WriteLine(i);
            Console.Beep();
            Console.ReadLine();
        }
    }
}




i get error "An object reference is required for the non-static field, method, or property 'text1.Program.method(int, int)'"
thank

推荐答案

由于Main是静态的,你不能使用静态方法中其余的程序类。



因此你需要一个程序类的实例。

更改

Since Main is static, you cannot use the rest of the Program Class inside your static method.

Therefore you need an instance of the Program Class.
Change
int j;        
j = pt(3, 4);





进入



Into

int j;
Program P = new Program();
j = P.pt(3, 4);





我建议在另一个类中编写pt(int,int)方法,但也许就是我。



I would recommend writing the pt(int,int) method in another class though, but maybe thats just me.


你好,



您从静态方法(Main)调用实例方法pt()。要纠正这个错误,要么(i)声明一个类型为program的变量,然后调用该方法,或者(2)将'static'添加到方法pt()的声明中。



Hi,

you are calling an instance method pt() from a static method (Main). To correct this error, either (i) declare a variable of type program and then call the method or (2) add 'static' to the declaration of method pt().

// option 1
int j;
Program program = new Program(); // new line
j = program.pt(3, 4);            // replace this line "j = pt(3, 4);"

// option 2
public static int pt(int l, int r)
{
    return l + r;
}


要求您创建程序的实例的替代方法是make pt()本身就是一个静态方法。由于 pt()仅对其参数进行操作(即它不引用其定义类型的任何实例成员),因此将其设置为静态是合适的选择。
An alternative to requiring that you create an instance of Program is that you make pt() itself a static method. Since pt() only operates on its parameters (i.e. it doesn't reference any instance members of its defining type) making it static is an appropriate choice.


这篇关于error非静态字段,方法或属性需要对象引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆