想象一下,我有一个"动物园"移动应用程序.它从在线服务器获取"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"). …