【问题标题】:Type of concrete class in base class with generic in c#c# 中具有泛型的基类中具体类的类型
【发布时间】:2018-09-20 07:10:23
【问题描述】:

我正在创建一个方法,该方法在 dto 和从基类覆盖的实体之间执行映射。我在 AuthorDto.cs 和 Dto.cs 中有以下类

public class AuthorDto : Dto<AuthorDto, Author>
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string LastName { get; set; }
    public string FullName { get; set; }

    public override void Map(IMap<AuthorDto, Author> mapper)
    {
        mapper.Map(t => t.FullName, t => t.Name + " " + t.LastName);
    }
}

public abstract class Dto<TDto, TEntity> where TDto : class where TEntity : class
{      
    public virtual void Map(IMap<TDto, TEntity> mapper) { }
}

我需要确保当我覆盖基本 Map 方法时,IMap 参数的第一个参数必须是 Dto 的实际具体类。

还有另一种方法可以执行此操作,而无需显式指示 Dto 中的第一个参数,从而获得类似的继承

public class AuthorDto : Dto<Author>

【问题讨论】:

    标签: c# generics inheritance types mapping


    【解决方案1】:

    我认为您是说要将 TD 类型限制为继承类?

    public abstract class Dto<TDto, TEntity> where TDto : Dto<TDto, TEntity> where TEntity : class
    

    这将确保 TDto 是一个继承自 Dto 基类的类。

    如果不显式定义 TDto 类型参数,您将无法继承,因为 Map 方法必须知道它。

    【讨论】:

      猜你喜欢
      • 2020-08-26
      • 1970-01-01
      • 2010-10-22
      • 1970-01-01
      • 1970-01-01
      • 2016-05-05
      • 2019-03-19
      • 2015-07-09
      • 2020-03-27
      相关资源
      最近更新 更多