如何将类型不变 setter 添加到协变接口?

How can I add a type invariant setter to a covariant interface?

我有一个类型 Shelter 需要协变,因此另一个 class* 中的覆盖可以 return 一个 Shelter<Cat>,其中 Shelter<Animal> 是预期的。由于classes在C#中不能协变或逆变,所以我加了一个接口:

public interface IShelter<out AnimalType>
{
    AnimalType Contents { get; }
}

但是,有一个地方为 IShelter(编译时类型)分配了一个新动物,我们可以肯定地知道被设置的动物将是一只猫。起初,我以为我可以在目录 属性 中添加一组并执行:

IShelter<Cat> shelter = new Shelter(new Cat());
shelter.Contents = new Cat();

但是添加setter是不可能的;

Error   CS1961  Invalid variance: The type parameter 'AnimalType' must be invariantly valid on 'IShelter<AnimalType>.Contents'. 'AnimalType' is covariant.

这是有道理的,否则我可以将猫舍传递给这个函数:

private static void UseShelter(IShelter<Animal> s)
{
    s.Contents = new Lion();
}

但是,我不会那样做。最好有一些方法将 setter 标记为不变的,这样 UseShelter 函数就只能分配一个 Animal,这样这将在编译时强制执行。我需要这个的原因是因为我的代码中有一个地方知道它有一个 Shelter<Cat>,并且需要将内容 属性 重新分配给一个新的 Cat.

到目前为止我找到的解决方法是在显式设置函数中添加一个 jucky 运行时类型检查;杰克!

public void SetContents(object newContents)
{
    if (newContents.GetType() != typeof(AnimalType))
    {
        throw new InvalidOperationException("SetContents must be given the correct AnimalType");
    }
    Contents = (AnimalType)newContents;
}

参数需要是object类型,这样才能在接口中指定这个函数。有没有办法在编译时强制执行此操作?

* 澄清一下,有一个函数:public virtual IShelter<Animal> GetAnimalShelter() 被覆盖并且 returns 一个 IShelter<Cat>:

public override IShelter<Animal> GetAnimalShelter(){
    IShelter<Cat> = new Shelter<Cat>(new Cat());
}

包括上面大部分代码的最小工作示例如下:

class Animal { }
class Cat : Animal { }
class Lion : Animal { }

public interface IShelter<out AnimalType>
{
    AnimalType Contents { get; }

    void SetContents(object newContents);
}

class Shelter<AnimalType> : IShelter<AnimalType>
{
    public Shelter(AnimalType animal)
    {
    }

    public void SetContents(object newContents)
    {
        if (newContents.GetType() != typeof(AnimalType))
        {
            throw new InvalidOperationException("SetContents must be given the correct AnimalType");
        }
        Contents = (AnimalType)newContents;
    }

    public AnimalType Contents { get; set; }
}

class Usage
{
    public static void Main()
    {
        IShelter<Cat> catshelter = new Shelter<Cat>(new Cat());
        catshelter.SetContents(new Cat());
        catshelter.SetContents(new Lion()); // should be disallowed by the compiler
    }
}

到目前为止我能想到的唯一解决方案是针对您的每个问题使用 2 个单独的接口(IShelterISpecificShelter):

// this replaces IShelter<Animal>
public interface IShelter
{
    Animal Animal { get; set; }
}

// this replaces IShelter<SpecificAnimal>
public interface ISpecificShelter<AnimalType> : IShelter where AnimalType : Animal
{
    new AnimalType Animal { get; set; }
}

// implementation
public class Shelter<AnimalType> : ISpecificShelter<AnimalType> where AnimalType : Animal
{
    private Animal _animal;

    // explicit implementation, so the correct implementation is called depending on what interface is used
    Animal IShelter.Animal { get { return _animal; } set { _animal = value; } }
    AnimalType ISpecificShelter<AnimalType>.Animal { get { return (AnimalType)_animal; } set { _animal = value; } }

    public Shelter()
    { }
}

用法:

// specific animal
ISpecificShelter<Cat> catShelter = new Shelter<Cat>();
catShelter.Animal = new Cat();
catShelter.Animal = new Lion(); // => compiler error!
Cat cat = catShelter.Animal;

// cast to general interface
IShelter shelter = catShelter;
Animal animal = shelter.Animal;

如果您想避免直接实例化 class,但 使用接口,您可以实施工厂模式:

public static class Shelter
{
    public static IShelter Create()
    {
        return new Implementation<Animal>();
    }

    public static IShelter Create(Animal animal)
    {
        return new Implementation<Animal>(animal);
    }

    public static ISpecificShelter<AnimalType> Create<AnimalType>() where AnimalType : Animal
    {
        return new Implementation<AnimalType>();
    }

    public static ISpecificShelter<AnimalType> Create<AnimalType>(AnimalType animal) where AnimalType : Animal
    {
        return new Implementation<AnimalType>(animal);
    }

    private class Implementation<AnimalType> : ISpecificShelter<AnimalType> where AnimalType : Animal
    {
        private Animal _animal;

        Animal IShelter.Animal { get { return _animal; } set { _animal = value; } }
        AnimalType ISpecificShelter<AnimalType>.Animal { get { return (AnimalType)_animal; } set { _animal = value; } }

        public Implementation()
        { }

        public Implementation(AnimalType animal)
        {
            _animal = animal;
        }
    }
}

用法:

var shelter = Shelter.Create();
shelter.Animal = new Lion();
// OR:
// var shelter = Shelter.Create(new Lion());
var animal = shelter.Animal;

var catShelter = Shelter.Create<Cat>();
catShelter.Animal = new Cat();
// OR:
// var catShelter = Shelter.Create(new Cat());
var cat = catShelter.Animal;

// cast is also possible:
shelter = (IShelter)catShelter;

这实际上取决于您的具体用例。您应该提供更多示例和信息,说明您到底想做什么以及为什么。

您想要实现的目标是不可能的,因为从技术上讲,您希望拥有既 covariant and contravariant. Limitations of each type of variance are well explained here in this SO answer

的界面

因此,如果您希望能够将更多派生类型(例如TDerived : T)设置为Contents 属性,您应该使用逆变接口:

public interface IShelter<in T>
{
    T Contents { set; }
}

另一方面,如果您希望能够将 Contents 传递给派生较少的类型(例如 T : TBase),您应该坚持使用当前的实现:

public interface IShelter<out T>
{
    T Contents { get; }
}

任何其他组合都可能导致运行时错误,这就是为什么编译器不允许您拥有同时协变和逆变的接口。

因此,要么使用两个不同的接口来实现您想要的,要么rethink/polish您的架构围绕这些类型。

在这种情况下,只需从接口中删除 setter 并使用具体类型(或使用 var 推断它,如本例所示)。毕竟,如果代码 "knows" 确定它添加了一只猫,它可能也知道避难所的具体类型。

interface IShelter<out AnimalType>
{
    AnimalType Contents { get; }
}

class Shelter<AnimalType> : IShelter<AnimalType>
{
    public Shelter(AnimalType animal)
    {
    }

    public void SetContents(AnimalType newContents)
    {
        Contents = newContents;
    }

    public AnimalType Contents { get; set; }
}

public class Usage
{
    public static void Main()
    {
        var catshelter = new Shelter<Cat>(new Cat());
        catshelter.SetContents(new Cat());
        catshelter.SetContents(new Lion()); // Is disallowed by the compiler
    }
}

Example on DotNetFiddle

System.Collections.Generic 下的许多 CLR class 遵循相同的模式。许多 classes 实现 IEnumerable<T>,它是协变的;但是如果你想调用允许你添加的方法,你必须将它引用为具体的 class 例如 List<T>。或者,如果您真的想通过界面添加,您可以使用 IList<T>。但是在任何情况下都没有一个单一的协变接口也允许你添加。