【问题标题】:Can I have multiple class constraints without setting the constraint to a type 'class' in C#我可以有多个类约束而不将约束设置为 C# 中的类型“类”吗
【发布时间】:2020-09-20 23:00:43
【问题描述】:

我有这个类,它是我的规范模式的一部分。 关注这个link

public class SpecificationEvaluator<TEntity> 
   where TEntity : BaseEntity

BaseEntity 只包含 id

例如

public class BaseEntity
{
   public int Id { get; set; }
}

这适用于我所有继承“BaseEntity”的实体

例如

Product : BaseEntity
Invoice : BaseEntity
Message : BaseEntity

现在我想在我的“用户”实体上使用规范模式,以便我可以提供规范/条件并获取用户列表。

但我的问题是我的项目“用户”实体没有继承“BaseEntity”,它继承了“IdentityUser”

例如

public class User : IdentityUser<int>
{
}

我知道我不能有多个类作为约束,但我可以有多个接口。

我知道我可以将约束设置为“类”

例如

public class SpecificationEvaluator<TEntity> 
where TEntity : class
{
}

但这不是有点违背了创建特定约束的目的吗?

问题 - 是否有另一种解决方案我可以实现同时拥有“BaseEntity”和“用户” 作为约束?

【问题讨论】:

标签: c# type-constraints generic-constraints


【解决方案1】:

在我看来,您可能必须这样做:

public interface IIdentityUser<T>
{
    T Id { get; set; }
}

public class SpecificationEvaluator<TEntity, T>
    where TEntity : IIdentityUser<T>
{ }

public class BaseEntity : IIdentityUser<int>
{
    public int Id { get; set; }
}

public class Product : BaseEntity { }
public class Invoice : BaseEntity { }
public class Message : BaseEntity { }

public class IdentityUser<T> : IIdentityUser<T>
{
    public T Id { get; set; }
}

public class User : IdentityUser<int>
{
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-21
    • 1970-01-01
    相关资源
    最近更新 更多