如何强制已实现的 Class 使用具有特定参数的实体?
How I can force an implemented Class to use an Entity which has a specific Parameter?
我的界面如下:
public interface IRepository<T> where T : class
{
T 是我的实体类型。
在这个界面中,我有一些方法将使用实体的 Id 属性。那么,当某些主体想要实现此接口时,我如何保证 实体具有 ID 属性?
救援界面!
定义接口如下:
// Why IEquatable<T>? Because you don't want identifiers that may not
// be able to prove that they're equal or not. Most commonly used
// types used as identifiers already implement IEquatable<T>. For example:
// int, Guid...
public interface ICanBeIdentifiable<TId> where TId : IEquatable<TId>
{
TId Id { get; }
}
...并按如下方式更改您的存储库接口签名:
public interface IRepository<T> where T : class, ICanBeIdentifiable<Guid>
...
...或者如果您想完全打开任何标识符类型的大门:
public interface IRepository<TId, T>
where TId : IEquatable<TId>
where T : class, ICanBeIdentifiable<TId>
主要缺点是您的域对象必须实现整个新接口,但值得付出努力。
您可以添加额外的接口,这将推动每个实体拥有 Id 属性
public interface IEntity
{
int Id { get; set; }
}
public interface IRepository<T> where T : class, IEntity
{
}
我的界面如下:
public interface IRepository<T> where T : class
{
T 是我的实体类型。
在这个界面中,我有一些方法将使用实体的 Id 属性。那么,当某些主体想要实现此接口时,我如何保证 实体具有 ID 属性?
救援界面!
定义接口如下:
// Why IEquatable<T>? Because you don't want identifiers that may not
// be able to prove that they're equal or not. Most commonly used
// types used as identifiers already implement IEquatable<T>. For example:
// int, Guid...
public interface ICanBeIdentifiable<TId> where TId : IEquatable<TId>
{
TId Id { get; }
}
...并按如下方式更改您的存储库接口签名:
public interface IRepository<T> where T : class, ICanBeIdentifiable<Guid>
...
...或者如果您想完全打开任何标识符类型的大门:
public interface IRepository<TId, T>
where TId : IEquatable<TId>
where T : class, ICanBeIdentifiable<TId>
主要缺点是您的域对象必须实现整个新接口,但值得付出努力。
您可以添加额外的接口,这将推动每个实体拥有 Id 属性
public interface IEntity
{
int Id { get; set; }
}
public interface IRepository<T> where T : class, IEntity
{
}