How to create function which lets you choose one of 3 parameters values?
So I have string returnType
which a d开发者_JS百科eveloper can choose to =
to JSON , XML or PRINT_R.
How to limit his choice and make VS 2008 or later suggest him what value (from that 3) string returnType
can be? (.net 3.5)
You have to use an enum instead of a string. Using strings for something like that is extremely ugly anyway - it will even require a runtime string comparison instead of a much cheaper integer or even bit comparison when using an enum (which is a number).
public enum DataFormat{ JSON=0, XML=1, PRINTR=2 }
public ReturnType SomeFunction( DataFormat format )
{
if( DataFormat.JSON == format )
return ....
//etc
}
If I understand the question right, enum
is the keyword you're looking for. So, you would declare a data type which represents the available return types:
public enum DataFormatType
{
Json,
Xml,
PrintR
}
and then in your function parameters, change string returnType
to DataFormatType returnType
. This will allow visual studio to suggest the values (this is called Code Completion or Intellisense) and the only valid values are those supplied in the enum.
Cheers, Alex
You can do a switch statement on the string. Then use a default for all invalid cases.
精彩评论