无法调用公共方法c#

时间:2015-01-29 21:49:51

标签: c# class methods private public

namespace ConsoleApplication3
{
    public class EncapulationTest
    {
        public static void publicMethod()
        {
            Console.WriteLine("This is the public method from the EncapsulationTest class!");
        }

        private static void privateMethod()
        {
            Console.WriteLine("This is the private method from the EncapsulationTest class!");
        }

    }
   public class Main
    {
       public static void Main()
       {
           publicMethod();
           Console.ReadLine();
       }
    }

我无法看到或调用publicMethod()方法作为选项,它说它在当前上下文中不存在。

任何理由,使用有限的理论示例。

Error 1 'Main': member names cannot be the same as their enclosing type

将代码扔进一个新项目并且bam!谢谢你们!

3 个答案:

答案 0 :(得分:1)

问题是您已直接致电publicMethod。与命名空间一样,类的名称范围彼此不同,因此虽然同一类中的方法可以仅通过名称引用,但另一个类中的方法必须具有明确指定的类。例如,考虑项目中的多个类是否具有方法publicMethod - 因此,调用必须是显式的。

请注意,虽然C#5.0只需要显式类名,但在C#6.0中,现在可以选择使用using语句指定类,以允许以这种方式指定其他类的方法。见here

在说明names cannot be the same as the enclosing type的错误提示上,这是因为命名了一个类和一个方法Main。这是一个例外,因为它的语法容易混淆地接近constructors,因此是不允许的。这就是为什么大多数模板会将Main方法放入Program类,而不是Main类。

答案 1 :(得分:0)

试试这个:

public static void Main()
{
   EncapulationTest.publicMethod();
}

答案 2 :(得分:0)

publicMethod是类EncapulationTest(sic)的静态成员。您如何从类Program中的代码中想到编译器应该知道publicMethod在哪里?它应该搜索它可以看到publicMethod的每个类吗?如果它找到多个,它会怎么做?

你需要告诉它该方法属于哪个类:

EncapulationTest.publicMethod();

现在它知道你要求publicMethod成为班级EncapulationTest的静态成员。

请注意,在EncapulationTest类本身中,您不需要添加类型,因为编译器将始终查找当前范围。另请注意,如果它是实例而不是静态方法,则不需要类型,而是具有该方法的类型的对象。