错误:成员名称不能与它们的包围类型[重复]

问题描述 投票:7回答:2

我是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); }
            }
        }
    }
}
c# class member names
2个回答
7
投票

执行此操作时:

Program prog = new Program();

C#编译器无法在此处告诉您是否要使用Program

namespace DriveInfos
{
    class Program  // This one?
    {
        static void Main(string[] args)
        {

或者如果您打算使用Program的其他定义:

    class Program
    {
        public int propertyInt
        {
            get { return 1; }
            set { Console.WriteLine(value); }
        }
    }

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

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); }
            }
        }
    }
}

因此,现在没有混乱-无论是对于编译器,还是对于您,当您在6个月内回来并尝试确定其作用时,都不会感到困惑!


2
投票

您有两个同名Program的类。重命名其中之一。

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

        class Program1
        {
            public int propertyInt
            {
                get { return 1; }
                set { Console.WriteLine(value); }
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.