在这个假设的情况下,是否有可能在C#<4中围绕泛型协方差进行最终运行?

在这个假设的情况下,是否有可能在C#<4中围绕泛型协方差进行最终运行?,第1张

概述假设我有一个小的动物继承层次结构: public interface IAnimal { string Speak();}public class Animal : IAnimal { public Animal() {} public string Speak() { return "[Animal] Growl!"; }}public 假设我有一个小的动物继承层次结构:

public interface IAnimal {    string Speak();}public class Animal : IAnimal {    public Animal() {}    public string Speak() {        return "[Animal] Growl!";    }}public class Ape : IAnimal {    public string Speak() {        return "[Ape] Rawrrrrrrr!";    }}public class Bat : IAnimal {    public string Speak() {        return "[Bat] Screeeeeee!";    }}

接下来,这是一个提供将字符串转换为IAnimals的方法的接口.

public interface ITransmogrifIEr<T> where T : IAnimal {    T Transmogrify(string s);}

最后,这是一个做到这一点的策略:

public class TransmogrifIEr<T> : ITransmogrifIEr<T> where T : IAnimal,new() {    public T Transmogrify(string s) {        T t = default(T);        if (typeof(T).name == s)            t = new T();        return t;    }}

现在,问题.是否可以替换标记为[1],[2]和[3]的部分,以便该程序能够正确编译和运行?如果你不接触[1],[2]和[3]以外的部分就不能这样做,你是否仍然可以从包含任意IAnimal实现的集合中的TransmogrifIEr的每个实例中获得一个IAnimal?你甚至可以开始形成这样的系列吗?

static voID Main(string[] args) {        var t = new TransmogrifIEr<Ape>();        Ape a = t.Transmogrify("Ape");        Console.Writeline(a.Speak());  // Works!        // But can we make an arbitrary collection of such animals?        var List = new List<TransmogrifIEr< [1] >>() {            // [2]        };        // And how about we call Transmogrify() on each one?        foreach (/* [3] */ transmogrifIEr in List) {            IAnimal ia = transmogrifIEr.Transmogrify("Bat");        }    }}
解决方法 你不能这样做,因为TransmorgifIEr< Ape>之间没有类型关系.和TransmorgifIEr< Bat>所以你不能把它们放在同一个通用列表中(List< object>除外).显而易见的解决方案只是使ITransmorgifIEr非泛型:

public interface ITransmogrifIEr{    IAnimal Transmogrify(string s);}

那你就可以了

var List = new List<ITransmogrifIEr>() {    new TransmorgifIEr<Ape>(),new TransmorgifIEr<Bat>() ...};
总结

以上是内存溢出为你收集整理的在这个假设的情况下,是否有可能在C#<4中围绕泛型协方差进行最终运行?全部内容,希望文章能够帮你解决在这个假设的情况下,是否有可能在C#<4中围绕泛型协方差进行最终运行?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/langs/1212910.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存