快速引用静态方法

本文关键字:静态方法 引用 | 更新日期: 2023-09-27 18:13:27

是否有可能调用不引用其类的方法?

例如,您有一个助手类:
class HelperTools
{
    public static void DoWork()
    { /*...*/ }
}

然后你需要调用它:

class MainClass
{
    public static void Main()
    {
        HelperTools.DoWork();
    }
}

是否可以在没有引用的情况下调用DoWork(); ?这样的:

public static void Main()
{
    DoWork();
}

为简单起见

快速引用静态方法

不完全是,但这里有5个模式让你接近:

namespace My.Namespace
{
    using H = MyHelperClass;
    public class MyHelperClass
    {
        public static void HelperFunc1()
        {
            Console.WriteLine("Here's your help!");
        }
    }
    public class MyHelperClass2
    {
        public static void HelperFunc4()
        {
            Console.WriteLine("Here's your help!");
        }
    }
    public interface IHelper{ }
    public static class HelperExtensions
    {
        public static void HelperFunc3(this IHelper self)
        {
            Console.WriteLine("Here's your help!");
        }
    }
    public class MyClass : MyHelperClass2, IHelper
    {
        private static readonly Action HelperFunc2 = MyHelperClass.HelperFunc1;
        private static void HelperFunc5() 
        {
            Console.WriteLine("Here's your help!");
        }
        public void MyFunction()
        {
            //Method 1 use an alias to make your helper class name shorter
            H.HelperFunc1();
            //Method 2 use a class property
            HelperFunc2();
            //Method 3 extend an interface that has extension methods.
            //Note: you'll have to use the this keyword when calling extension
            this.HelperFunc3();
            //Method 4 you have access to methods on classes that you extend.
            HelperFunc4();
            //Method 5 put the helper method in your class
            HelperFunc5();
        }
    }
}

No。Java有这样导入静态的概念,但c#没有。(在我看来,一个没有任何线索的裸DoWork()是不理想的。)

晚了几年,但也许这将帮助别人…

使用using static指令来引用静态类:(在c# 6中引入)

using static HelperTools;
class MainClass
{
    public static void Main()
    {
        DoWork();
    }
}
---------------- HelperTools.cs--------------------
class HelperTools
{
    public static void DoWork()
    { /*...*/ }
}

您可以在不引用类名的情况下调用DoWork的唯一位置是在类本身中。例如,如果您向HelperTools:

添加一个非静态方法
public void foo()
{
    DoWork();
}

你可以在里面调用DoWork,即使foo()不是静态的。