Greetings all,
I have a list of "Types" meeting a certain critera that I obtained through reflection. Each of the types is a different feature that the user will potentially choose at runtime. If I add more subclasses later, this dynamic implementation would save my having to remember to update the user control is the idea here.
开发者_Python百科The list of types is nice, but it'd be nice to display something more meaningful than the Name as it's written in code. For example, instead of "RacingBikeDesigner", I'd like to display "Racing Bike Designer", and maybe even display other properties associated with that type like "Description" so that the user knows what that particular choice does.
So I guess the question is, given a Type, how can I provide a more meaningful representation to the user? Could I maybe add a static field to each subclass and call that from the Type, or could I perhaps use a type converter somehow?
The user control (ListBox, ComboBox, etc) is bound to the return value below, but it's not user-friendly:
List<string> LeftHandedUserChoices = new List<string>();
Type[] AllTypesInThisAssembly = Assembly.GetAssembly(typeof(UserChoices)).GetTypes();
foreach (Type _currentType in AllTypesInThisAssembly)
if (_currentType.IsSubclassOf(typeof(UserChoices)))
LeftHandedUserChoices.Add(_currentType.Name);
return LeftHandedUserChoices;
Cheers, Q
You have a couple of options for doing this. You could use an attribute on your type for the description, or put it in a static field/property on the Type and retrieve that using reflection.
If localization is an issue, you will probably want to store the resource string name, and display the resource value at runtme.
Add custom C# Attributes to your types.
One method is for you to parse class names based on the naming convention you are using (looks like Pascal in your case). For instance RacingBikeDesigner
will become Racing Bike Designer
. Here is a parsing example.
精彩评论