c# - 使用泛型进行隐式转换
问题描述
我本质上是在尝试向上转换一个对象,但我不知道如何处理泛型。下面是一个超级人为的例子,但它说明了我正在处理的情况。也许我需要一个隐式运算符,但我不确定在这种情况下会是什么样子。
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");
}
}
}
解决方案
感谢@kalten,我找到了这个解决方案:
public interface Animal<out T> where T : Cat
你可以看到它在这里工作:https ://repl.it/@austinrr/FlippantLonelyTab#main.cs
推荐阅读
- javascript - 是否可以使用 Chrome 打印在最后一页的底部添加页脚?
- python - Python:尝试在 HTTPRequest 的字符串中查找单词
- xml - 将 xml 映射到对象
- apache - 如何使用 mod_auth_openidc 注销
- laravel - Laravel Largon Xdebug
- flutter - 推到这个屏幕并弹出它们之间的所有屏幕
- c# - XML序列化具有附加属性的通用列表
- react-native - 成功添加数据后如何导航到相应的配置文件屏幕
- node.js - 如何在没有私钥的情况下将我的元掩码钱包中的 erc20 代币发送到其他地址?
- python - 当我按 InlineKeyboardButton 多次且速度过快时出现“消息未修改”