如何从静态 main() 方法中调用一个方法?

11

我有一个包含Main方法和一个函数的控制台应用程序。

如何从Main方法中调用该函数?

我知道下面的代码是行不通的:

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

5
GetCommandLine()是一个静态方法吗? - Catch22
6
当你忘记基础知识时,最好的方法是重新学习它们。至少我是这么做的。 - R. Martinho Fernandes
8个回答

27

还有一个选项

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

在一堆年份里,当我们可以立即从静态main()方法中调用时,为什么C#不行呢?这其中是否有什么理由? - Soner from The Ottoman Empire

13

GetCommandLine函数改为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();
        }
    }
}

1
没问题 :-). 祝你再次掌握基础好运! - Kees C. Bakker

2
static class Program
{        
    [STAThread]
    static void Main()
    {
        string btchid = Program.GetCommandLine();
    }

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

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

1
一个针对你问题的线性搜索方法:

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;
    }
}
}

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

GetCommandLine 必须是一个静态函数


0

字符串 btchid = classnamehere.GetCommandLine();假设GetCommandLine是静态的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接