不知道将传入什么对象类型,如果它是 FishDTO 的类型,它有不同的路线来生成 uri,如果它不是鱼而不是哺乳动物,则应遵循标准路线。有没有更干净的方法来做到这一点?除了使用 type 有没有更好的方法使用as?这有效,但它看起来很难看:
public Uri GetAnimalImageUrl(object animalResult)
{
if (animalResult.GetType() == typeof(FishDTO))
{
return new Uri(GetFishImageUrl((FishDTO)animalResult));
}
var mammal = (MammalDTO)animalResult;
var mammalUrl = GetMammalImageUrl(mammal);
if (!string.IsNullOrEmpty(mammalUrl))
{
return new Uri(mammalUrl);
}
_logger.Error("Image not found for animal");
return null;
}
Run Code Online (Sandbox Code Playgroud)