【问题标题】:Can I receive generic type or list of this type我可以接收泛型类型或这种类型的列表吗
【发布时间】:2018-03-28 14:23:39
【问题描述】:

我有像下面这样的 BaseEntity 类。

public abstract class BaseEntity : Notifiable
{
}

我想创建一个接收泛型类型的类,这个类型可以是 BaseEntity 或 BaseEntity 的 IEnumerable 这可能吗?

public abstract class BaseDTO<T> where T : BaseEntity OR IEnumerable<BaseEntity>
{}

【问题讨论】:

  • 为什么在这里使用泛型?只需使用IEnumerable&lt;BaseEntity&gt;,如果它是单个元素,则您的可枚举是单个元素。将它作为基类或基类的枚举是没有意义的。
  • 你不能这样做。但是@RonBeyer 是对的,您为什么想要 这样做?这似乎是一个经典的XY problem
  • 我认为使用 Base 或 enumerable 对继承类的适用性更简单

标签: c# asp.net generics inheritance


【解决方案1】:

我不确定这是最好的答案,但我这样做了。

我创建了一个接口 IBaseDTO 并实现了两个类(BaseDTO 和 BaseListDTO)

public interface IBaseDTO
{
}

public abstract class BaseDTO<T> : IBaseDTO
        where T : BaseEntity
{
}

public abstract class BaseListDTO<T> : IBaseDTO
    where T : IEnumerable<BaseEntity>
{
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-05
    相关资源
    最近更新 更多