执行非Program.cs文件的输出

本文关键字:输出 文件 cs Program 执行 | 更新日期: 2023-09-27 17:53:57

我已经在VS 2010中创建了一个新的控制台应用程序。

我在Program.cs文件下写了一些代码。现在我创建了另一个类,并在那里编写了代码。现在,当我从另一个类执行程序时,从program.cs文件调用输出。如何使项目设置,使输出反映从另一个类,而不是程序。cs文件?

执行非Program.cs文件的输出

Xor power -我将尽可能在这里回答你的评论

如果我需要调用其他类的主方法,而不是任何用户定义的方法?

控制台应用程序只能有1 main方法——这是应用程序的入口点。

所以要在你的程序中添加一个新的Main方法,你需要改变哪个类首先启动,要做到这一点,只需从program .cs中删除Main方法并将其添加到你的新类中,如下所示

class NewClass
{
    static void Main(string[] args)
    {
        Console.WriteLine("hello, world");
    }
}

不,这是简单的显示到控制台:如果我需要从任何其他类输出到控制台,而不是Program.cs

另一方面,如果您需要获得一个类来写入控制台,并且它不是起始类,那么您必须指定一个方法并使用console。以Dave &狐狸先生已经在上面展示了。如下所示

class Program
{
    static void Main(string[] args)
    {
        // use a instance of a class to write
        NewClass myNewClass = new NewClass();
        myNewClass.WriteOutPut();
        // use a static class
        NewClass2.WriteOutPut();
        // finally read back so that they we can see what was ouputted
        Console.ReadLine();
    }
}
/// <summary>
/// this is an instance class
/// </summary>
public class NewClass
{
    public void WriteOutPut()
    {
        Console.WriteLine("hello");
    }
}
/// <summary>
/// this is a static class
/// </summary>
public static class NewClass2
{
    public static void WriteOutPut()
    {
        Console.WriteLine("hello");
    }
}

使用。net运行时,任何控制台应用程序都将具有Main()函数。这是应用程序的入口点,运行时执行该入口点以使应用程序运行。这可能在Program.cs中。

为了从控制台应用程序中的ANY类向控制台窗口输出文本,您只需要输入:

Console.WriteLine("Some message")

Console.Write("Some message without a linefeed after it")

输出到应用程序的控制台窗口。

为了从控制台应用程序中的ANY类的控制台读取输入,您将使用

Console.ReadLine(**variable to take in input**);

Console.Read(**variable to take in input**);

这里是。net 4中Console类的完整API的链接

您需要从主方法(通常位于Program.cs中)中的其他类创建对象并调用它的方法。

c#中的main方法通常用属性"[STAThread]"来标识。

在main方法中如果你的类名是FooBar:
    [STAThread]
    static void Main(string[] args)
    {
        FooBar fooBar = new FooBar();
        fooBar.RunMethod();
    }

我迟到了。但是不要在Program.cs中写Main Method,而把它写在你正在执行的其他文件中。或者使用c# cli编译器来编译和执行而不是Visual studio