I'm not sure how to better word the question, but I've run into the following problem with trying to create a Dictionary of generic interfaces more than once. Often this has come about when trying to create registry type collections which handle different types:
namespace GenericCollectionTest
{
[TestFixture]
public class GenericCollectionTest
{
interface IValidator<T>
{
bool Validate(T item);
}
class TestObject
{
public int TestValue { get; set; }
}
private Dictionary<Type, IValidator<object>> Validators = new Dictionary<Type, IValidator<object>>();
class BobsValidator : IValidator<TestObject>
{
public bool Validate(TestObject item)
{
if (item.TestValue != 1)
{
return false;
}
}
}
[Test]
public void Test_That_Validator_Is_Working()
{
var Test = new TestObject {TestValue = 1};
Validators.Add(typeof(BobsValidator), new BobsValidator());
Assert.That(Validators[typeof(TestObject)].Validate(Test));
}
}
}
However, compilation fails because BobsValidator is not assignable to parameter type IValidator. Basically, I don't need type safety outside of the validator, but once I'm inside, I don't the consumer of the interface to have to cast it to the type they want to use.
In Java, I could:
Dictionary<Type, IValidator<?>>
I know I can do something like this (ala IEnumerable):
interface IValidator
{
bool Validate(object item);
}
interface IValidator<T> : IValidator
{
bool Validate(T item);
}
abstract class ValidatorBase<T> : IValidator<T>
{
protected bool Validate(object item)
{
return Validate((T)item);
}
protected abstract bool Validate(T item);
}
Then make the dictionary take IValidator instead and extend ValidatorBase, but it seems like there must be a better way that I'm not seeing. Or, is this just poor design overall? It seems like I need some kind of structure like this:
WhatTheHecktionary<T, IValidator<T>>
Thanks!