How to “import” a static class in C#?

后端 未结 9 1439
挽巷
挽巷 2020-12-28 19:08

I have created a public static class utils.cs I want to use it in other classes without prefixing method with utils, what\'s the syntax to do this ?

9条回答
  •  臣服心动
    2020-12-28 19:23

    What Jon Skeet is not telling you is that you can have global static members in c#. Your utility class can indeed become a reality in c#.

    Unfortunately, Microsoft has determined that the very process of constructing such members as above mere "normal" development, and requires that you forge them from raw intermediate language. Such a powerful pattern is above common syntax highlighting and friendly icons).

    Here is the requisite sequence of utf-8 characters (guard it carefully):

    .assembly globalmethods {}
    
    .method static public void MyUtilMethod() il managed 
    {
      ldstr "Behold, a global method!"
      call void [mscorlib]System.Console::WriteLine(class System.String) 
      ret
    }
    

    (You could compile this example by invoking ilasm.exe from the SDK command prompt, remembering to use the /dll switch)


    ilasm.exe output:

    Microsoft (R) .NET Framework IL Assembler. Version 2.0.50727.4016 Copyright (c) Microsoft Corporation. All rights reserved. Assembling 'globalmethods.msil' to DLL --> 'globalmethods.dll' Source file is ANSI

    global.msil(7) : warning -- Reference to undeclared extern assembly 'mscorlib'. Attempting autodetect

    Assembled global method MyUtilMethod

    Creating PE file

    Emitting classes:

    Emitting fields and methods: Global Methods: 1;

    Emitting events and properties: Global Writing PE file Operation completed successfully


    Once you have compiled your newly created assembly (as "globalmethods.dll" for example), it's just a matter of adding a reference in Visual Studio. When that is complete, you better be sitting down, because it will be time to write some real code:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Reflection;
    
    namespace TestGlobalMethod
    {
        class Program
        {
            static void Main(string[] args)
            {
    
                "MyUtilMethod".Call();
    
                Console.ReadKey();
    
            }
    
        }
    
        /// 
        /// Reduces the amount of code for global call
        /// 
        public static class GlobalExtensionMethods 
        {
            public static void Call(this string GlobalMethodName)
            {
                Assembly.Load("globalmethods")
                    .GetLoadedModules()[0].GetMethod(GlobalMethodName)
                        .Invoke(null,null);
    
            }
    
        }
    
    
    }
    

    Yes, you just called a Global method in c#.

    *Please don't use this, it's for example only :-) Also, you could probably write your global methods in another language that support them, such as VB.NET.

提交回复
热议问题