不能隐式转换的MyType

不能隐式转换的MyType

本文介绍了不能隐式转换的MyType<富>到MyType的<的IFoo>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道这是否是一个协变和逆变的问题,但我不能得到这个工作。下面是代码:

I am not sure if this is a Covariance and Contravariance issue but I cannot get this working. Here is the code:

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 方法。任何想法如何解决这个问题呢?

For some reason, I cannot pass PaginatedDto<PersonDto> as PaginatedDto<IDto> to ProcessDto method. Any idea how can I solve this issue?

推荐答案

是的,这是一个变化的问题。您需要创建一个接口(仅限接口和委托可CO /逆变) IPaginatedDto<出TDto> 其中的DTO 不能有setter方法(否则你不能使用退出):

Yes this is a variance issue. You need to create an interface (only interfaces and delegates can be co/contravariant) IPaginatedDto<out TDto> where the Dtos cannot have a setter (otherwise you cannot use out):

public interface IPaginatedDto<out TDto> where TDto : IDto
{
    int PageIndex { get; set; }
    int PageSize { get; set; }
    int TotalCount { get; set; }
    int TotalPageCount { get; set; }
    bool HasNextPage { get; set; }
    bool HasPreviousPage { get; set; }
    IEnumerable<TDto> Dtos { get; }
}

和您的 PaginatedDto< TDto> 将实现此接口:

public class PaginatedDto<TDto> : IPaginatedDto<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; }
}

和使用该接口在你的方法:

And use the interface in your method:

private static void ProcessDto(IPaginatedDto<IDto> paginatedDto)
{

    //Do work...
}

这篇关于不能隐式转换的MyType&LT;富&GT;到MyType的&LT;的IFoo&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 13:11