繁体   English   中英

C#Console.WriteLine()在Main()外部不起作用

[英]C# Console.WriteLine() Not working Outside of Main()

抱歉,如果这是重复的,则无法解决我遇到的问题。 我正在使用以下代码块:

IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties();
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
Console.WriteLine("Interface information for {0}.{1}     ",
        computerProperties.HostName, computerProperties.DomainName);
foreach (NetworkInterface adapter in nics)
{
    IPInterfaceProperties properties = adapter.GetIPProperties();
    Console.WriteLine(adapter.Description);
    Console.WriteLine(String.Empty.PadLeft(adapter.Description.Length, '='));
    Console.WriteLine("  Interface type ... : {0}", adapter.NetworkInterfaceType);
    Console.WriteLine("  Physical Address ........... : {0}",
               adapter.GetPhysicalAddress().ToString());
    Console.WriteLine("  Is receive only.............. : {0}", adapter.IsReceiveOnly);
    Console.WriteLine("             Multicast......... : {0}", adapter.SupportsMulticast);
    Console.WriteLine();
}

当我在没有调试的情况下运行并且此代码在Main()方法中时, Console.WriteLine()将输出输出。 但是,当我将其放入public static void类中时,输出为空白。 谁能解释为什么会这样,我该怎么办。 我仍在学习C#,所以我确定这是初学者的错误。 任何帮助,将不胜感激。

我猜想您其他类中的代码永远不会执行。 您不需要该类是public static void的(不确定这是否可行),但是您想要使用的方法是public static void的。

这是您希望其他班级的样子:

public class OtherClass {

    public static void Method() {

        // Console.WriteLine code here

    }
}

然后您的主体应调用该方法:

public class OriginalClass {

    public static void Main(String[] args) {

        OtherClass.Method();

    }

}

如果您要使用其他方法/函数而不是类,则它将如下所示:

public class OriginalClass {

    public static void Main(String[] args) {

        Method();

    }

    public static void Method() {

        // Console.WriteLine code here

    }

}

“主”是.NET环境中的一种特殊方法。 这是每个.NET程序的“入口点”。

当您的应用程序/程序运行时,将调用Main并执行此方法中的每个命令。

如果将代码放入其他方法或类中,而没有在Main中调用它,则显然不会发生任何事情。 因此,如果要运行其他方法,则必须在Main内部调用它。

希望它有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM