错误:成员名称不能与其封闭类型相同

Muh*_*ail 7 c# class names member

我是C#的新手,我正在学习它,它只是一个虚拟测试程序.我收到了这篇文章标题中提到的错误.下面是C#代码.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace DriveInfos
{
    class Program
    {
        static void Main(string[] args)
        {
            Program prog = new Program();
            prog.propertyInt = 5;
            Console.WriteLine(prog.propertyInt);
            Console.Read();
        }

        class Program
        {
            public int propertyInt
            {
                get { return 1; }
                set { Console.WriteLine(value); }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Dr *_*ang 7

当你这样做:

Program prog = new Program();
Run Code Online (Sandbox Code Playgroud)

C#编译器无法判断您是否要使用Program此处:

namespace DriveInfos
{
    class Program  // This one?
    {
        static void Main(string[] args)
        {
Run Code Online (Sandbox Code Playgroud)

或者,如果您的意思是使用另一个定义Program:

    class Program
    {
        public int propertyInt
        {
            get { return 1; }
            set { Console.WriteLine(value); }
        }
    }
Run Code Online (Sandbox Code Playgroud)

这里最好的办法是更改内部类的名称,它将为您提供:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace DriveInfos
{
    class Program
    {
        static void Main(string[] args)
        {
            MyProgramContext prog = new MyProgramContext();
            prog.propertyInt = 5;
            Console.WriteLine(prog.propertyInt);
            Console.Read();
        }

        class MyProgramContext
        {
            public int propertyInt
            {
                get { return 1; }
                set { Console.WriteLine(value); }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

所以现在没有混淆 - 不是为了编译器,也不是为了你在6个月后回来并尝试弄清楚它在做什么!

  • 编译器本来可以理解,因为类实际上是`Program`和`Program.Program`.根本问题是C#规范定义你不能这样做.在VB中,您可以创建一个具有相同名称的嵌套类.我想设计选择是为了避免模糊和构造函数语法的混淆 (2认同)