As Mike and Arne point out, no...System.Type is not a valid type for use
in a switch.
Mike's suggestion of using the type name could work for you.
Alternatively, if there's a very small number of System.Type values you
want to handle, you could just write a series of if/else statements. If
there are too many choices for that to be maintainable in your opinion,
another alternative is to create a Dictionary<System.Type, Func<Style>>,
and then initialize the dictionary with delegates that do the right
thing. For example:
initialize in an appropriate place:
Dictionary<System.Type, Func<Style>> mptypestyle =
new Dictionary<System.Type, Func<Style>>();
mptypestyle.Add(typeof(MenuItem), () => MenuItemStyle());
// add others as necessary...
then elsewhere:
public Style GetStyle(Type type)
{
Style style;
if (mptypestyle.TryGetValue(type, out style))
{
return style;
}
return null;
}
Pete
Hi Pete,
I was trying to do something similar to your suggestion but I wasn't
able to associate each type with a method. Only with a function.
With your approach I am having an error (sorry am I not familiar with
Func):
cannot convert from 'out System.Windows.Style' to 'out
System.Func<System.Windows.Style>'
I did the change:
Func<Style> style;
if (_types.TryGetValue(type, out style)) {
return style;
}
But now I get:
Cannot implicitly convert type 'System.Func<System.Windows.Style>' to
'System.Windows.Style'
How to solve this?
Following your suggestion of using Func I am using the following:
public class StyleFactory {
private Dictionary<Type, Func<Style>> _types = new
Dictionary<Type, Func<Style>>();
public StyleFactory() {
_types.Add(typeof(Menu), () => MenuStyle());
_types.Add(typeof(MenuItem), () => MenuItemStyle());
} // StyleFactory
public Style GetStyle<T>() {
return (Style)GetStyle(typeof(T));
} // GetStyle
public Style GetStyle(Type type) {
Func<Style> style;
if (_types.TryGetValue(type, out style)) {
return style;
}
return null;
} // GetStyle
Thanks,
Miguel
I had done before something similar to what you did but returning a
class based on a interface.
In this case I wasn't able to use that approach.