我不确定如何更好地表达这个问题,但是在尝试创建多个泛型接口的字典时,我遇到了以下问题。通常在尝试创建处理不同类型的注册表类型集合时会遇到这种情况:
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));
}
}
}
然而,编译失败是因为BobsValidator不能赋值给参数类型IValidator。基本上,在验证程序之外,我不需要类型安全性,但一旦进入验证程序,我希望接口的使用者不必将其转换为他们想要使用的类型。
在Java中,我可以:
Dictionary<Type, IValidator<?>>
我知道我可以像IEnumberable一样做这样的事情:
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);
}
那么可以让dictionary采用IValidator,并扩展ValidatorBase,但似乎还有更好的方法我没看到。或者说,这是整体设计不佳吗?看起来我需要类似于这样的结构:
WhatTheHecktionary<T, IValidator<T>>
谢谢!