Assigning (non)constant value to enum
I'm trying 开发者_如何学Goto assign a short to a enum like this:;
public enum ValueRepresentation : short
{
ApplicationEntity = short.Parse("AE"),
AgeString = short.Parse("AS")
}
This however, obviously, doesn't work. But is there a quick fix to make this work?
Cheers
No. Enum values are always compile-time constants. If you want them to be values created by running code, you'll have to autogenerate your source code.
(How exactly would parsing "AS" work anyway?)
Of course, another alternative is to not use enums. They may not be the most appropriate solution for what you're trying to do.
As Jon says, this just isn't going to work and autogeneration may be what you need instead.
If you have a list of these values like "AE", "AS" etc, take a look at t4 templates (part of Visula Studio), it would be pretty easy to write a simple template to loop through your list and spit out the correct enum code.
The MSDN docs are here: http://msdn.microsoft.com/en-us/library/bb126445.aspx
I also found Oleg SYch's blog very helpful: http://www.olegsych.com/2007/12/text-template-transformation-toolkit/
I'd also suggest using VS2010 if possible, it has really nice support for t4, but they still work fine under VS2008 if not.
if you want enums to have short values, declare the enum in the usual way with values associated and cast the enum to a short or the short to the enum:
public enum ValueRepresentation
{
AE =1,
AS = 2
}
private short AsShort(ValueRepresentation value)
{
return (short)value;
}
private ValueRepresentation ShortAsValue(short number)
{
return (ValueRepresentation)number;
}
精彩评论