开发者

I have scope issues with an enum

Basically, i have one class with a code of a chess game, it has an enum class..

namespace WindowsFormsApplication1
{
    enum STATE { PROMOTION, CASTLING, CHECK, CHECKMATE, DONOTHING };

.....

i want to refer to it from my Form code: here is the code:

namespace WindowsFormsApplication1
{

    public partial class ChessBoard:开发者_JAVA百科 Form
    {
public STATE Gamestate { set; get; }

......

i get this:

Error 1 Inconsistent accessibility: property type 'WindowsFormsApplication1.STATE' is less accessible than property 'WindowsFormsApplication1.ChessBoard.Gamestate' D:\Documents and Settings\Dima\My Documents\Visual Studio 2008\Projects\ChessBoardGame\ChessBoardGame\ChessBoard.cs 15 22 ChessBoardGame

Why do i get it and how can i prevent it ?


You need to declare your enum as public in WindowsFormsApplication1:

namespace WindowsFormsApplication1
{
    public enum STATE { PROMOTION, CASTLING, CHECK, CHECKMATE, DONOTHING };

.....


First off, please don't use SCREAMING CAPS in C#. Use PascalCaseIdentifiers (or camelCaseIdentifiers for locals); they are much more pleasant to read.

Second, you might be missing some states. It's not a bad idea to track whether the game is in a state where an en passent capture is permitted. You also do not have a state for stalemate or other "drawn" situations.

Third, to address your actual question: the error is telling you what is wrong. "State" and "GameState" have inconsistent accessibility. You omitted to put an accessibility modifier on State, so it gets the default accessibility which is "internal" for a top-level enum. "GameState" is a public property of a public class. So you are saying "the type of this thing which is available to the public is an internal implementation detail of my assembly", which obviously seems a little bit impossible, so the compiler flags it.

The first question I would ask myself is "why is the class public?" Do you intend to have this class created by assemblies outside of this one?

If you intend the class to be public then:

  • make the property private or internal, or
  • make the enum public

If you intend the class to be internal then make the class internal.


Even if it doesn't answer your question (cause this is already done by @FreeAsInBeer) you should really consider to stick to some more common naming convention and put the default value as first. So the result could look something like:

public enum State
{
    DoNothing,
    Promotion,
    Castling,
    Check,
    Checkmate
}

By putting DoNothing as first member of your enum you declare this as the default value (0). So if someone asks for a default(State) he simply gets DoNothing which sounds quite good for a default value.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜