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!谢谢你们!
答案 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
类本身中,您不需要添加类型,因为编译器将始终查找当前范围。另请注意,如果它是实例而不是静态方法,则不需要类型,而是具有该方法的类型的对象。