如何从静态main()调用方法
本文关键字:调用 方法 main 静态 | 更新日期: 2023-09-27 17:50:34
我有一个控制台应用程序,其中包含一个Main
方法和一个函数。
我如何从Main
方法进行函数调用?
我知道下面的代码不会工作
static void Main(string[] args)
{
string btchid = GetCommandLine();// GetCommandline is a mthod which returns a string
}
还有
var p = new Program();
string btchid = p.GetCommandLine();
使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();
}
}
}
您可以将函数更改为静态并调用它。这一切。
static class Program
{
[STAThread]
static void Main()
{
string btchid = Program.GetCommandLine();
}
private static string GetCommandLine()
{
string s = "";
return s;
}
}
解决问题的线性搜索方法:
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;
}
}
}
GetCommandLine
必须是静态函数
string btchid = classnamehere.GetCommandLine();
假设GetCommandLine
是静态的
像这样:
[STAThread]
static void Main(string[] args) {
string btchid = GetCommandLine();// GetCommandline is a mthod which returns a string
}
static string GetCommandLine(){
return "Some command line";
}