0

是否有可能在不引用其类的情况下调用方法?

例如,您有一个辅助类:

class HelperTools
{
    public static void DoWork()
    { /*...*/ }
}

然后你需要调用它:

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

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

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

只是为了简单。

4

4 回答 4

6

不完全是,但这里有 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();
        }
    }
}
于 2013-05-14T00:01:37.907 回答
3

不,Java 有像这样导入静态的概念,但 C# 没有。(国际海事组织,DoWork()对实施所在的位置没有任何线索的裸体是不理想的。)

于 2013-05-13T23:48:04.303 回答
1

晚了几年,但也许这会帮助别人......

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

using static HelperTools;

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

---------------- HelperTools.cs--------------------
class HelperTools
{
    public static void DoWork()
    { /*...*/ }
}
于 2018-09-16T15:50:19.547 回答
0

您可以DoWork在不引用类名的情况下调用的唯一位置是类本身。例如,如果您将非静态方法添加到HelperTools

public void foo()
{
    DoWork();
}

您可以DoWork从其中调用,即使它foo()不是静态的。

于 2013-05-13T23:55:26.770 回答