【问题标题】:Implicit Conversion with Generics使用泛型进行隐式转换
【发布时间】:2020-12-29 17:35:19
【问题描述】:

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

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");
    }
  }

}

【问题讨论】:

  • 您需要使用out 通用修饰符 (docs)。像这样使用它:public interface Animal&lt;out T&gt;
  • 接口真的应该在他们的名字前面加上一个 I...
  • 正如 kalten 所写,您需要只有接口才有可能的协方差 (stackoverflow.com/questions/2719954/…)(幸运的是,Animal&lt;T&gt; 是一个接口)
  • 我在接口前加了“我”。

标签: c# generics polymorphism


【解决方案1】:

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

public interface Animal<out T> where T : Cat

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-12
    • 1970-01-01
    • 2017-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多