2014-09-11 36 views
0

我是C#和編程的新手,今天我開始學習C#。我已經在我的教程書的功能部分中介紹過了,但是我無法掌握代碼中的錯誤。我正在做這本書上寫的東西,但這個錯誤正在出現。谷歌無法幫助我,因爲大部分谷歌搜索結果都有複雜的解決方案,這些解決方案超出了我的頭腦。所以,如果有人花了幾分鐘的時間,並指出我在我的代碼中做錯了什麼,我將不勝感激。非靜態字段,方法或屬性需要對象引用ConsoleApplication5.Program.myFirst(int,int)

的IDE正顯示出此錯誤:

Error 1 An object reference is required for the non-static field, method, or property 'ConsoleApplication5.Program.myFirst(int, int)' C:\Users\Eion\documents\visual studio 2013\Projects\ConsoleApplication5\ConsoleApplication5\Program.cs 17 25 ConsoleApplication5

而且我的代碼是:

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

namespace ConsoleApplication5 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Console.Write("First: "); 
      int ab = int.Parse(Console.ReadLine()); 
      Console.Write("Second: "); 
      int ba = int.Parse(Console.ReadLine()); 
      int my1Res= myFirst(ab, ba); 
      Console.WriteLine("The result is " + my1Res); 

     } 
     public int myFirst(int ab, int ba) 
     { 
      int myRes = ab + ba; 
      return myRes; 
     } 
    } 
} 

回答

5

你需要讓myFirst方法是靜態的。

public static int myFirst(int ab, int ba) 

不能調用從靜態上下文非靜態方法沒有一個實例。

有關更多詳細信息,請參見Compiler Error CS0120

相關問題