开发者

Is it possible to create an enum whose instance can't be created but can be used for readonly purpose

I created an enum where I stored some table names. I want it to be used to get the name of the table like ds.Tables[BGuestInfo.TableName.L_GUEST_TYPE.ToString()].

public class a
{
      public enum TableName : byte
            {
                L_GUEST_TYPE = 0
                ,L_AGE_GROUP = 1
                ,M_COMPANY = 2
                ,L_COUNTRY = 3
                ,L_EYE_COLOR = 4
                ,L_GENDER = 5
                ,L_HAIR_COLOR = 6
                ,L_STATE_PROVINCE = 7
                ,L_STATUS = 8
                ,L_TITLE = 9
                ,M_TOWER = 10
                ,L_CITY = 11
                ,L_REGISTER_TYPE = 12
            }
}

class b 
{
    a.TableName x; //trying to restrict this 
    ds.Tables[a.TableName.L_GUEST_TYPE] //accessible and can be used like this
}

This is my enum. Now I have not created any instance of this enum so that no one can use it for other than read only开发者_JAVA百科 purpose.

For this enum to be accessible in outer classes as well I have to make it public which means some outer class can create its object as well.

So what can i do so as to restrict its instance creation.


Enums are value types. You cannot create objects/instances from them.

By definition, enums are read only. You cannot modify defined enum values, only use them.

You can restrict visibility by using access modifiers - you can make the enum private to your class:

class b 
{
    private enum TableName : byte
    {
      L_GUEST_TYPE = 0
      ,L_AGE_GROUP = 1
      ,M_COMPANY = 2
      ,L_COUNTRY = 3
      ,L_EYE_COLOR = 4
      ,L_GENDER = 5
      ,L_HAIR_COLOR = 6
      ,L_STATE_PROVINCE = 7
      ,L_STATUS = 8
      ,L_TITLE = 9
      ,M_TOWER = 10
      ,L_CITY = 11
      ,L_REGISTER_TYPE = 12
    }

    public void myMethod(DataSet ds)
    {
      ds.Tables[TableName.L_GUEST_TYPE] //accessible and can be used like this
    }
}


I would probably do something like this:

public class Table
{
  public static readonly Company = new Table("T_Company");
  public static readonly Title = new Table("T_Title");
  public static readonly City = new Table("T_City");

  private string name;

  public string Name { get { return name; } }

  private Table(string name)
  {
    this.name = name;
  }
}

class b 
{
    // ...

    // use it like this:
    ds.Tables[Table.Company.Name];
}

This is similar to the "enum pattern". You write a class which could be used like an enum.

You can add other properties to the Table class, not only the Name. You could also put all the tables into a list (in the constructor) and provide a static property to access all the tables.

And last but not least, if you have different areas in your applications (e.g. modules), you could derive the Table class in each area in order to add additional tables which are only visible to this area.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜