Use static function from a class without naming the class

前端 未结 4 1699
轻奢々
轻奢々 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:01

    If you're looking to define a globally-scoped procedure then the short answer is no, you can't do this in c#. No global functions, procedures or objects.

    In C# everything apart from namespaces and types (class, struct, enum, interface) must be defined inside a type. Static members (fields, properties and methods) can be used without an instance of the class, but only by referencing the type that owns them. Non-static members need an instance of the owning class.

    This is fundamental to the syntax of the language. C# is neither C nor C++, where you can define global objects, functions and procedures.

    0 讨论(0)
  • 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
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-20 17:20

    I routinely have

    static Action<object> o = s => Console.WriteLine(s);
    

    in my code which makes debug output so much less noisy. That way I can call Console's static Writeline() much easier. Would that help?

    0 讨论(0)
  • 2021-01-20 17:24

    In C#? Not possible. Because it's a full OOP programming language and it was designed to work with objects you can't use functions outside the scope of an object. When calling static methods you have to specify the class where that static method lives...

    Class.StaticMethod();
    

    you can only use the short-hand notation if this method is call from within the same class...

    StaticMethod();
    

    But remember that you will not get access to instance members because static methods donot belong to instance of an object

    Update based on comment

    Looks like it will be possible to call static members without having to specify the class that declares it in C# 6, and you will be able to reference classes directly in using statements...in similar fashion to Java...more info here

    0 讨论(0)
提交回复
热议问题