加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 09:27:38 所属栏目:百科 来源:网络整理
导读:假设我有一个小的动物继承层次结构: public interface IAnimal { string Speak();}public class Animal : IAnimal { public Animal() {} public string Speak() { return "[Animal] Growl!"; }}public class Ape : IAnimal { public string Speak() { retur
假设我有一个小的动物继承层次结构:

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>() ...
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读