为什么我的代码不起作用?
using System;
namespace Enum
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Test.FruitCount);
}
}
public class Test
{
enum Fruits { Apple, Orange, Peach }
public const int FruitCount = Enum.GetNames(typeof(Fruits)).Length;
}
}
我收到错误
无法解析符号"GetNames"
为什么?如何解决?
因为您已经将它设置为一个只能是编译时常量的常量。
这项工作:
enum Fruits { Apple, Orange, Peach }
static readonly int FruitCount = Enum.GetNames(typeof(Fruits)).Length;
MSDN
常量是不可变的值,在编译时是已知的,在程序的生命周期内不会更改。
更新:您还必须将命名空间从Enum
更改为其他名称空间。
试试这个代码,
public int fruitCount = Enum.GetValues(typeof(Fruits)).Length;
请记住将文件的名称空间从Enum
更改为类似的名称空间
因为您的命名空间也是Enum。这使编译器感到困惑。试试这个:
namespace Enum
{
class Program
{
static void Main(string[] args)
{
Test test = new Test();
Console.WriteLine(test.FruitCount);
}
}
public class Test
{
enum Fruits { Apple, Orange, Peach }
public int FruitCount
{
get
{
return System.Enum.GetNames(typeof(Fruits)).Length;
}
}
}
}
我基本上用System.Enum.GetNames
完全限定了Enum