C#:控制台应用程序 - 静态方法 [英] c# : console application - static methods

查看:172
本文介绍了C#:控制台应用程序 - 静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在C#中,控制台应用程序,在方案类,这是默认情况下,所有的方法都必须以



 <$ C $沿着静C>静态无效的主要(字串[] args)


解决方案

成员函数不的有无的是静态的;但如果他们的的静态的,需要你实例化一个程序对象,以调用成员方法。



通过静态方法:

 公共类节目
{
公共静态无效的主要()
{
的System.Console.WriteLine(Program.Foo());
}

公共静态字符串美孚()
{
返回富;
}
}



不带静电的方法(换句话说,需要你实例程序):

 公共类节目
{
酒店的公共静态无效的主要()
{
的System.Console.WriteLine(新计划()富());
}

公共字符串美孚()//注意这不是静态的了
{
返回富;
}
}



必须是静态的,否则你必须告诉编译器如何实例化程序类,这可能是也可能不是一个简单的任务。


why in C#, console application, in "program" class , which is default, all methods have to be static along with

static void Main(string[] args)

解决方案

Member functions don't have to be static; but if they are not static, that requires you to instantiate a Program object in order to call a member method.

With static methods:

public class Program
{
    public static void Main()
    {
        System.Console.WriteLine(Program.Foo());
    }

    public static string Foo()
    {
        return "Foo";
    }
}

Without static methods (in other words, requiring you to instantiate Program):

public class Program
{
    public static void Main()
    {
        System.Console.WriteLine(new Program().Foo());
    }

    public string Foo() // notice this is NOT static anymore
    {
        return "Foo";
    }
}

Main must be static because otherwise you'd have to tell the compiler how to instantiate the Program class, which may or may not be a trivial task.

这篇关于C#:控制台应用程序 - 静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆