6
我不確定這是否是協變和逆變問題,但我無法使其工作。下面是代碼:不能隱式地將MyType <Foo>轉換爲MyType <IFoo>
public interface IDto { }
public class PaginatedDto<TDto> where TDto : IDto {
public int PageIndex { get; set; }
public int PageSize { get; set; }
public int TotalCount { get; set; }
public int TotalPageCount { get; set; }
public bool HasNextPage { get; set; }
public bool HasPreviousPage { get; set; }
public IEnumerable<TDto> Dtos { get; set; }
}
public class PersonDto : IDto {
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public int Age { get; set; }
}
class Program {
static void Main(string[] args) {
var people = new List<PersonDto> {
new PersonDto { },
new PersonDto { },
new PersonDto { },
};
var paginatedPersonDto = new PaginatedDto<PersonDto>() {
Dtos = people
};
//ProcessDto doesn't accept this
ProcessDto(paginatedPersonDto);
}
private static void ProcessDto(PaginatedDto<IDto> paginatedDto) {
//Do work...
}
}
出於某種原因,我無法通過PaginatedDto<PersonDto>
爲PaginatedDto<IDto>
到ProcessDto
方法。任何想法如何解決這個問題?
啊,我笨頭!我實際上嘗試過,但將方法留作'ProcessDto(PaginatedDto paginatedDto)',並且如預期的那樣,這並不起作用。 –
tugberk