首页 > 解决方案 > 使用泛型进行隐式转换

问题描述

我本质上是在尝试向上转换一个对象,但我不知道如何处理泛型。下面是一个超级人为的例子,但它说明了我正在处理的情况。也许我需要一个隐式运算符,但我不确定在这种情况下会是什么样子。

using System;
using System.Collections.Generic;

class MainClass {
  public static void Main (string[] args) {

    var cats = new Dictionary<string, IAnimal<ICat>>()
    {
      { "paws", new Tabby() },
      { "teeth", new MountainLion() }
    };

    foreach (var cat in cats)
    {
      cat.Value.talk();
    }
  }

  public interface IAnimal<T> where T : ICat
  {
    void talk();
  }

  public interface ICat
  {
  }

  public class HouseCat : ICat
  {
  }

  public class BigCat : ICat
  {
  }

  public class MountainLion : IAnimal<BigCat>
  {
    public void talk() {
      Console.WriteLine("Rawr!");
    }
  }

  public class Tabby : IAnimal<HouseCat>
  {
    public void talk() {
      Console.WriteLine("Meow");
    }
  }

}

标签: c#genericspolymorphism

解决方案


感谢@kalten,我找到了这个解决方案:

public interface Animal<out T> where T : Cat

你可以看到它在这里工作:https ://repl.it/@austinrr/FlippantLonelyTab#main.cs


推荐阅读