我是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); }
}
}
}
}
执行此操作时:
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个月内回来并尝试确定其作用时,都不会感到困惑!
您有两个同名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); }
}
}
}
}