[英]Implicit Conversion with Generics
I'm essentially trying to upcast an object but I don't know how to deal with the generics.我实际上是在尝试上调 object,但我不知道如何处理 generics。 Below is a super-contrived example but it illustrated a situation I'm working with.下面是一个超级人为的例子,但它说明了我正在处理的情况。 Perhaps I need an implicit operator but I'm not sure what that would look like in this scenario.也许我需要一个隐式运算符,但我不确定在这种情况下会是什么样子。
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");
}
}
}
Thanks to @kalten I arrived at this solution:感谢@kalten,我找到了这个解决方案:
public interface Animal<out T> where T : Cat
You can see it working here: https://repl.it/@austinrr/FlippantLonelyTab#main.cs你可以看到它在这里工作: https://repl.it/@austinrr/FlippantLonelyTab#main.cs
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.