开发者

Can C# can run code before or after main like in objective C

开发者 https://www.devze.com 2023-01-24 08:06 出处:网络
http://gcc.gnu.org/onlinedocs/gcc-2.95.3/objc-features_1.html#SEC2 The GNU Objective-C runtime provides a way that allows you to execute code before the execution of the program enters the main funct

http://gcc.gnu.org/onlinedocs/gcc-2.95.3/objc-features_1.html#SEC2

The GNU Objective-C runtime provides a way that allows you to execute code before the execution of the program enters the main function. The code is executed on a per-class and a per-category basis, through a special class method +load.

Update: the answers I read below are not satisfactory. There's nothing special to call a function from a main program. The question is about HOOKING the SYSTEM that is the SYSTEM calls a function without YOUR PROGRAM even aware of it at RUNTIME.

Instead of Objective C see this article on Visual C++ (thanks to stackoverflow guy who answer my previous question): http://www.codeguru.com/cpp/misc/misc/threadsprocesses/article.php/c6945

Otherwise there was no need for Objective C Runtime to include this load method. main entry point of course exis开发者_开发技巧ts for Objective C program and if it suffices to just call a static method WITHIN the main method there's no big deal :)


In OOP languages since main is always inside a class, there is always a way to run some code before main function is executed. In Java it's called static initialization block. A similar mechanism is also available in C#. See this link

Code example:

namespace CSharpConsoleTest
{
  class Program
  {
    static Program()
    {
        Console.WriteLine("Test123");
    }

    static void Main(string[] args)
    {
        Console.WriteLine("Test111");
    }
  }
}

Well the point is to be able to initialize static variables inside the class since they are created before instance variables.


What your are looking for in c# are called class constructors(runs before) and class destructors(runs after)

Here is a link to a tutorial...

http://csharp.net-tutorials.com/classes/constructors-and-destructors/

0

精彩评论

暂无评论...
验证码 换一张
取 消