2011-04-20 67 views
6

我有一个控制台应用程序和一个Main方法和函数。如何从静态main()中调用方法?

如何从Main方法进行函数调用?

我知道下面的代码将无法正常工作

static void Main(string[] args) 
{    
    string btchid = GetCommandLine();// GetCommandline is a mthod which returns a string 
} 
+3

是GetCommandLine()一个静态方法? – Catch22 2011-04-20 09:58:45

+5

忘记他们时记住基本知识的最好方法是再次研究它们。至少这就是我所做的。 – 2011-04-20 10:00:13

回答

13

还有

var p = new Program(); 
string btchid = p.GetCommandLine(); 
9

充分利用​​static

namespace Lab 
{ 
    public static class Program 
    { 
     static string GetCommandLine() 
     { 
      return "Hellow World!"; 
     } 

     static void Main(string[] args) 
     { 
      System.Console.WriteLine(GetCommandLine()); 
      System.Console.ReadKey(); 
     } 
    } 
} 
+0

哇:)完成..谢谢 – Priyanka 2011-04-20 09:59:39

+1

没问题:-)。祝您再次掌握基础知识! – 2011-04-20 10:00:51

1

您可以将函数更改为静态并调用它。就这样。

0

​​必须是静态函数

0

string btchid = classnamehere.GetCommandLine(); 假设​​是静态

0

事情是这样的:

[STAThread] 
static void Main(string[] args) { 
    string btchid = GetCommandLine();// GetCommandline is a mthod which returns a string 
} 

static string GetCommandLine(){ 
    return "Some command line"; 
} 
0
static class Program 
{   
    [STAThread] 
    static void Main() 
    { 
     string btchid = Program.GetCommandLine(); 
    } 

    private static string GetCommandLine() 
    { 
     string s = ""; 
     return s; 
    } 
} 
0

线性搜索方法您的问题:

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

namespace LinearSearch 
{ 
class Program 
{ 

    static void Main(string[] args) 
    { 
     int var1 = 50; 
     int[] arr; 
     arr = new int[10]{10,20,30,40,50,60,70,80,90,100}; 
     int retval = linearsearch(arr,var1); 
     if (retval >= 1) 
     { 
      Console.WriteLine(retval); 
      Console.Read(); 
     } 
     else 
     { Console.WriteLine("Not found"); Console.Read(); } 
    } 

    static int linearsearch(int[] arr, int var1) 
    { 
     int pos = 0; 
     int posfound = 0; 
     foreach (var item in arr) 
     { 
      pos = pos + 1; 
      if (item == var1) 
      { 
       posfound = pos; 
       if (posfound >= 1) 
        break; 
      }  
     } 
     return posfound; 
    } 
} 
} 
相关问题