作者热门文章
- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我在理解如何在现实世界中使用协变和逆变时遇到了一些困难。
到目前为止,我见过的唯一示例是相同的旧数组示例。
object[] objectArray = new string[] { "string 1", "string 2" };
如果我能看到它在其他地方使用,那么很高兴看到一个允许我在开发过程中使用它的示例。
最佳答案
// Contravariance
interface IGobbler<in T> {
void gobble(T t);
}
// Since a QuadrupedGobbler can gobble any four-footed
// creature, it is OK to treat it as a donkey gobbler.
IGobbler<Donkey> dg = new QuadrupedGobbler();
dg.gobble(MyDonkey());
// Covariance
interface ISpewer<out T> {
T spew();
}
// A MouseSpewer obviously spews rodents (all mice are
// rodents), so we can treat it as a rodent spewer.
ISpewer<Rodent> rs = new MouseSpewer();
Rodent r = rs.spew();
为了完整性......
// Invariance
interface IHat<T> {
void hide(T t);
T pull();
}
// A RabbitHat…
IHat<Rabbit> rHat = RabbitHat();
// …cannot be treated covariantly as a mammal hat…
IHat<Mammal> mHat = rHat; // Compiler error
// …because…
mHat.hide(new Dolphin()); // Hide a dolphin in a rabbit hat??
// It also cannot be treated contravariantly as a cottontail hat…
IHat<CottonTail> cHat = rHat; // Compiler error
// …because…
rHat.hide(new MarshRabbit());
cHat.pull(); // Pull a marsh rabbit out of a cottontail hat??
关于c# - 协变和逆变现实世界的例子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2662369/
笙歌 痞性. 剩余 青怏 洒脱 现实 搁浅° 软萌 路途 娼妓 离骚 逐你 微尘 迷魂 ▼ 扎心 堇夏 残年っ ╭淡妆╮ 24K.纯疯 隐痛
我正在尝试不费吹灰之力地实现完全有效的持久性无知。不过我有很多问题: 最简单的选项 这真的很简单——可以像在 SOA 中那样使用 Spring Data 注释对实体进行注释(但让它们真正执行逻辑)?除
我想完成一项简单的任务。 我在可变宽度容器中有一个图像。 容器的宽度可以为 300、400、700 或 900 像素。这是通过媒体查询完成的图像应占据该容器的所有宽度。所以它也将是 300、400、7
我在使用 Storyboards AutoRotation 和 iPhone 时遇到问题。我已经将一个非常简单的项目与 3 个 View Controller 放在一起,并将其上传到 gitHub 以
我是一名优秀的程序员,十分优秀!