how to declare global function or method using c#?

后端 未结 4 457
逝去的感伤
逝去的感伤 2021-01-04 11:56

Can anyone tell me how to declare a global function in c#, similar to what a Module does in VB.net? I need to call a function that can be called in my form1, fo

4条回答
  •  没有蜡笔的小新
    2021-01-04 12:50

    If you're using C# 6.0 or later, you could use using static.

    For example,

    using static ConsoleApplication.Developer;
    
    namespace ConsoleApplication
    {
        class Program
        {
            static void Main(string[] args)
            {
                // Global static function, static shorthand really 
                DeveloperIsBorn(firstName: "Foo", lastname: "Bar")
                    .MakesAwesomeApp()
                    .Retires();
            }
        }
    }
    
    namespace ConsoleApplication
    {
        class Developer
        {
            public static Developer DeveloperIsBorn(string firstName, string lastname)
            {
                return new Developer();
            }
    
            public Developer MakesAwesomeApp()
            {
                return this;
            }
    
            public Developer InsertsRecordsIntoDatabaseForLiving()
            {
                return this;
            }
    
            public void Retires()
            {
               // Not really
            }        
        }
    }
    

    One more example:

    using static System.Console;
    
    namespace ConsoleApplication7
    {
        class Program
        {
            static void Main(string[] args)
            {
                WriteLine("test");
            }
        }
    }
    

提交回复
热议问题