小编use*_*386的帖子

c#如何将泛型类型参数转换并传递给内部函数?

想象一下,我有一个"动物园"移动应用程序.它从在线服务器获取"Animals"并将它们存储在本地数据库中.

Class Animal
Class Bird : Animal
Class Fish : Animal
Class Pelican : Bird
Class Penguin : Bird
Run Code Online (Sandbox Code Playgroud)

所以我创建了一个具有以下功能的GetAnimalsFromServerService类.

public Task<Animal[]> GetAnimalsFromServer<T>() where T : Animal, new() {
    if (typeof(T) == typeof(Bird)) {
        return GetBirdsFromServer<T>();
    } else if (typeof (T) == typeof(Fish)){
        return GetFishFromServer<T>();
    }
}


private Task<Bird[]> GetBirdsFromServer<T>() where T : Bird, new() {
    // Bird specific functionality here.
    if (typeof(T) == typeof(Pelican)) {
        return _serverConnection.GetPelicansFromServer();
    } else if (typeof (T) == typeof(Penguin)){
        return _serverConnection.GetPenguinsFromServer();
    }
}
Run Code Online (Sandbox Code Playgroud)

这不能编译,因为T的类型为"Animal"而不是Type"Bird"(而GetBirdsFromServer需要类型为"Bird"). …

c# generics parameters types

5
推荐指数
1
解决办法
119
查看次数

标签 统计

c# ×1

generics ×1

parameters ×1

types ×1