Use static function from a class without naming the class

前端 未结 4 1737
轻奢々
轻奢々 2021-01-20 16:54

How can I access functions from a class without having to name that class every time? I know how to use \"using\" so that I don\'t have to name the namespace but I was hopin

4条回答
  •  孤独总比滥情好
    2021-01-20 17:18

    using static yournamespace.yourclassname;

    then call the static class method without class name;

    Example:

    Class1.cs

    namespace WindowsFormsApplication1
    {
        class Utils
        {
            public static void Hello()
            {
                System.Diagnostics.Debug.WriteLine("Hello world!");
            }
        }
    }
    

    Form1.cs

    using System.Windows.Forms;
    using static WindowsFormsApplication1.Utils;
    
    namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
    
            public Form1()
            {
                InitializeComponent();
                Hello();    // <====== LOOK HERE
            }
        }
    }
    

提交回复
热议问题