创建一个通用的泛型集合 - 字典协变

3

我不确定如何更好地表达这个问题,但是在尝试创建多个泛型接口的字典时,我遇到了以下问题。通常在尝试创建处理不同类型的注册表类型集合时会遇到这种情况:

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>>

谢谢!


你的抽象版本是一个很好的起点。从那里开始,你只需要一个工厂,在运行时获取正确的实现。问题在于,你可以向调用代码公开的所有内容都是IValidator<object>,因此每个实现都必须具有该方法。 - Caleb
1个回答

0

为了将BobsValidator分配给IValidator,您需要将接口的泛型参数变成协变的,这将允许您的IValidator指向更具体的类型,如IValidator。

interface IValidator<out T>
{
   bool Validate(T item);
}

然而,你会发现你无法编译,因为你的接口不再是类型安全的,所以编译器不会允许。那么为什么它不再是类型安全的呢?想象一下:

using NUnit.Framework;
namespace GenericCollectionTest
{
    [TestFixture]
    public class GenericCollectionTest
    {
        //.NET Compiling Error:
        //"Invalid variance: The type parameter 'T' must be contravariantly valid ..."
        interface IValidator<out T>
        {
            //Error: "Parameter must be type-safe. Invalid variance..."
            bool Validate(T item);
        }

        class MyObject
        {
            public int TestValue { get; set; }
        }

        class YourObject
        {
            public int CheckValue { get; set; }
        }

        class MyValidator : IValidator<MyObject>
        {
            public bool Validate(MyObject item)
            {
                return (item).TestValue == 1;
            }
        }

        class YoursValdator : IValidator<YourObject>
        {
            public bool Validate(YourObject item)
            {
                return (item).CheckValue == 1;
            }
        }

        [Test]
        public void Test_That_Validator_Is_Working()
        {
            //.NET compiler tries to prevent the following scenario:

            IValidator<object> someObjectValidator = new MyValidator();
            someObjectValidator.Validate(new YourObject()); // Can't use MyValidator to validate Yourobject

            someObjectValidator = new YoursValdator();
            someObjectValidator.Validate(new MyObject()); // Can't use YoursValidator to validate MyObject

        }
    }
}

为了解决这个问题,我建议您尝试使用非泛型作为基类,以便您可以将验证器存储在字典中。请看以下代码是否适用于您的情况:
using System;
using System.Collections.Generic;
using NUnit.Framework;
namespace GenericCollectionTest
{
    [TestFixture]
    public class GenericCollectionTest
    {

        interface IValiadtor
        {
            bool Validate(object item);
        }

        abstract class ValidatorBase<T> : IValidator<T>
        {
            public bool Validate(object item)
            {
                return Validate((T)item);
            }

            public abstract bool Validate(T item);
        }

        interface IValidator<T> : IValiadtor
        {
            //Error: "Parameter must be type-safe. Invalid variance..."
            bool Validate(T item);
        }

        class MyObject
        {
            public int TestValue { get; set; }
        }

        class YourObject
        {
            public int CheckValue { get; set; }
        }

        class MyValidator : ValidatorBase<MyObject>
        {
            public override bool Validate(MyObject item)
            {
                return (item).TestValue == 1;
            }
        }

        class YoursValdator : ValidatorBase<YourObject>
        {
            public override bool Validate(YourObject item)
            {
                return (item).CheckValue == 1;
            }
        }

        [Test]
        public void Test_That_Validator_Is_Working()
        {
            Dictionary<Type, IValiadtor> Validators = new Dictionary<Type, IValiadtor>();
            Validators.Add(typeof(MyObject), new MyValidator() );
            Validators.Add(typeof(YourObject), new YoursValdator());

            var someObject = new MyObject();
            someObject.TestValue = 1;
            Assert.That(Validators[someObject.GetType()].Validate(someObject));


        }
    }
}

是的,如果您注意到问题底部,我建议采用这种方法。不过,我想知道是否有其他方法。谢谢! - Nishmaster
我不知道是否由于类型安全问题存在其他更好的方法。如果您阅读我的示例,就会非常清楚为什么.NET设计师不想要那样做。我已经多次使用了这种基类技术,并且一直运作良好。它强制我的团队使用接口进行编码,并允许您的架构或框架与特定类型一起工作。最后一个建议是尝试返回验证委托(在这种情况下为Predicate),但我不知道它如何帮助您解决上述情况。 - dsum
尽管我试图避免走这条路,但这确实是正确的答案。虽然我建议了它,但我会给出这个答案。干杯! - Nishmaster

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接