简体   繁体   中英

Why does “Enum” fail to compile when “enum” succeeds in c# .NET?

Why does changing enum to E num cause compile errors?

Generally in c# one can use ac# type or its .NET equivalent.

Example:

string jeff = "Atwood";  // string type
String name = "Jeff";    // System.String

" string (C# Reference) "
" The string type represents a sequence of zero or more Unicode characters.
string is an alias for String in the .NET Framework."

The following .NET console application succeeds for " enum ":

using System;

namespace UnhappyWithSystemEnum
{
    enum FirstEnum { Nothing = 0, Something = 666 };

    class CapitalE
    {
        static void Main(string[] args)
        {
            Console.WriteLine(FirstEnum.Nothing);
            Console.WriteLine(FirstEnum.Something);
            Console.WriteLine("Press ENTER to Exit");
            Console.ReadLine();
        }
    }
}

output:

Nothing
Something
Press ENTER to Exit

However, changing " enum " to " E num" causes multiple errors:

    Enum FirstEnum { Nothing = 0, Something = 666 };

error:

'invalid-global-code.FirstEnum':
    property or indexer must have at least one accessor

Please explain.

MSDN References:
" Enum Class "
" enum (C# Reference) "

This happens because string is an alias for String , but enum is not the same as Enum :

The enum keyword defines a new type that is inherited from System.Enum with members as static fields.

enum MyEnum
{
    Member
}

is the equivalent (and I think it's actually the real generated CIL) of:

public class MyEnum : System.Enum
{
    public static int Member;
}

If you use Enum instead:

Enum MyEnum
{
     Member
}

would be like:

StringBuilder MyEnum
{
    Member
}

which obviously makes no sense for the compiler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM