是否可以创建一个无法创建实例但可用于只读目的的枚举
我创建了一个枚举,在其中存储了一些表名。我希望它用于获取表的名称,例如 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
}
这是我的枚举。现在我还没有创建此枚举的任何实例,因此没有人可以将其用于只读目的以外的用途。
为了使这个枚举也可以在外部类中访问,我必须将其公开,这意味着某些外部类也可以创建其对象。
那么我可以做什么来限制它的实例创建。
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 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
枚举是值类型。您无法从它们创建对象/实例。
根据定义,枚举是只读的。您不能修改定义的枚举值,只能使用它们。
您可以使用访问修饰符来限制可见性 - 您可以使枚举您的班级私有:
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:
我可能会做这样的事情:
这类似于“枚举模式”。您编写一个可以像枚举一样使用的类。
您可以向 Table 类添加其他属性,而不仅仅是 Name。您还可以将所有表放入列表中(在构造函数中)并提供静态属性来访问所有表。
最后但并非最不重要的一点是,如果您的应用程序中有不同的区域(例如模块),您可以在每个区域中派生 Table 类,以便添加仅对该区域可见的附加表。
I would probably do something like this:
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.