【问题标题】:Using static method from other file without class name [duplicate]使用其他文件中没有类名的静态方法[重复]
【发布时间】:2021-11-02 01:40:05
【问题描述】:

我尝试使用类似 using Printer; 但它不起作用。

我只想使用 P(); 而不是 Printer.P();

文件打印机.cs

using System;

namespace animals
{
    public class Printer
    {
        public static void P()
        {
            P("\a");
        }

        public static void P(object val, bool doEnterAfterLine = true, bool printInOneLine = false)
        {
            P(val.ToString());
            if (doEnterAfterLine)
                Console.WriteLine(); //enter
        }

        static void P(bool printSeparator = false)
        {
            if (printSeparator == false)
                return;

            P("---------------------------------------------------------", true);
        }


        static void P(string value = "none", bool modifyColor = false, bool ding = false, bool printInOneLine = false)
        {
            var oldColor = Console.ForegroundColor;

            if (modifyColor)
                Console.ForegroundColor = ConsoleColor.Magenta;

            if (printInOneLine)
                Console.Write(value + " ");
            else
                Console.WriteLine(value);

            Console.ForegroundColor = oldColor; //recover color

            if (ding)
            {
                Console.Write("\a");
            }
        }
    }
}

文件 Program.cs

using System;
// this resolve problem: using static animals.Printer;
 
namespace animals 
{
     class Program
     {
         static void Main(string[] args)
         {           
             Printer.P(); // it works
             P();         // info: does not exist in current context                        
         }
     }
}

【问题讨论】:

  • 你的意思是using static animals.Printer.P;?
  • @Omar 不是 using static animals.Printer;?
  • 可能,我不记得了。 using - static modifier
  • 除非您没有显示所有代码...Printer 类无效...P(“/a”)...?
  • 你应该有更大的事情需要担心,但是如果你查看使用文档,你会发现你需要什么

标签: c#


【解决方案1】:

使用using static <namespace>.<class>; 访问<class> 的成员,无需限定其名称。

using static animals.Printer;

【讨论】:

  • 点击复选标记将这个答案标记为正确如果它解决了您的问题
  • 使用静态animals.Printer; --> 工作得很好!谢谢!
  • 可能值得补充的是,我从未见过在生产代码中使用它,很可能是因为它打破了一些关于方法调用的基本假设,因此可能导致比它保存的几个字符更多的问题。跨度>
猜你喜欢
  • 2013-01-12
  • 1970-01-01
  • 1970-01-01
  • 2010-12-12
  • 2020-08-06
  • 2021-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多