Circular definition in a constant enum

后端 未结 4 1742
别跟我提以往
别跟我提以往 2021-01-04 01:18

I\'m trying to create a constant of type Enum but I get a error.. My enum is:

public enum ActivityStatus
{
    Open = 1,
    Close = 2
}
         


        
相关标签:
4条回答
  • 2021-01-04 01:42

    You should not create a variable with the same name of a class or enum.

    Maybe it will work if you specify the namespace, like :

    public class CreateActivity
    {
        public int Id;
        public const TheNamespace.ActivityStatus ActivityStatus =
            TheNamespace.ActivityStatus.ActivityStatus.Open;
    }
    
    0 讨论(0)
  • 2021-01-04 01:45

    Because the c# compiler intepretes the third ActivityStatus in:

    public const ActivityStatus ActivityStatus = ActivityStatus.Open; 
    

    as the name of the constant being defined instead than the name of the enumeration - hence the circular reference: you are definining a constant in terms of the constant itself.

    In C# you can use the same name for members and types, and usually resolve ambiguities specifying the fully qualified names (i.e. adding the namespace), but in my experience it is not a good idea, it makes code confusing: the compiler can figure out which is which, but the poor human reading the code has an hard time figuring out if a certain name refers to a class or type or member.

    0 讨论(0)
  • 2021-01-04 01:56

    If private usage only: You can change ActivityStatus to readonly field and move setting of default value to constructor.

    If public usage: You can use property with getter only.

    In most of the code analyzers additional namespace will be treated as redundance in your code.

    0 讨论(0)
  • 2021-01-04 01:56

    To avoid from the Circular Definition Problem in C#, You can reference/call the variable/type/member etc with full qualified name like

    Namespace..Member/Type/ etc
    

    Hope you will fix the error by now.

    0 讨论(0)
提交回复
热议问题