Reputation: 83254
I want to enforce type constraint when I define a 'type mapping' dictionary, such as this:
internal static class BindingResources
{
/// <summary>
/// Key== IDialogWindowVM, Value ==Window
/// </summary>
public static readonly Dictionary<Type, Type> ViewModelDictionary =
new Dictionary<Type, Type>()
{
{typeof(CreateGroupVM), typeof(CreateGroupUI)},
{typeof(CreateNewNetworkVM), typeof(CreateNewNetwork)}
};
}
I want to ensure that CreateGroupVM
is of the interface IDialogWindowVM
, and CreateGroupUI
is inherited from Window
class. If these conditions are not satisfied that I shall get a compilation error instead of a runtime error.
If this even possible, if yes, how to do it? If no, why?
Upvotes: 0
Views: 35
Reputation: 27021
You can use a helper method.
public static Dictionary<Type, Type> ViewModelDictionary
{
get
{
var d = new Dictionary<Type, Type>();
void Add<U, V>()
where U : IDialogWindowVM
where V : Window => d.Add(typeof(U), typeof(V));
Add<CreateGroupVM, CreateGroupUI>();
Add<CreateNewNetworkVM, CreateNewNetwork>();
return d;
}
}
Upvotes: 1