C# 如何强制实现的类使用具有特定参数的实体?
我的界面如下:C# 如何强制实现的类使用具有特定参数的实体?,c#,generics,inheritance,interface,implementation,C#,Generics,Inheritance,Interface,Implementation,我的界面如下: public interface IRepository<T> where T : class { 公共接口i假设,其中T:class { T是我的实体的类型。 在这个接口中,我有一些方法将使用实体的Id属性。那么,当有人想要实现这个接口时,我如何保证,实体具有Id属性呢?拯救接口 定义一个接口,如下所示: // Why IEquatable<T>? Because you don't want identifiers that may not /
public interface IRepository<T> where T : class
{
公共接口i假设,其中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; }
}
//为什么IEquatable?因为您不需要可能不可用的标识符
//能够证明他们是否相等。最常用的
//用作标识符的类型已实现IEquatable。例如:
//int,Guid。。。
公共接口不可识别,其中TId:I可识别
{
TId Id{get;}
}
…并按如下方式更改存储库接口签名:
public interface IRepository<T> where T : class, ICanBeIdentifiable<Guid>
...
公共接口i位置,其中T:class,可识别
...
…或者如果您想绝对打开任何标识符类型的门:
public interface IRepository<TId, T>
where TId : IEquatable<TId>
where T : class, ICanBeIdentifiable<TId>
公共接口IRepository
哪里TId:IEquatable
其中T:类,可识别
主要缺点是您的域对象必须实现整个新接口,但这是值得努力的。拯救接口 定义一个接口,如下所示:
// 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; }
}
//为什么IEquatable?因为您不需要可能不可用的标识符
//能够证明他们是否相等。最常用的
//用作标识符的类型已实现IEquatable。例如:
//int,Guid。。。
公共接口不可识别,其中TId:I可识别
{
TId Id{get;}
}
…并按如下方式更改存储库接口签名:
public interface IRepository<T> where T : class, ICanBeIdentifiable<Guid>
...
公共接口i位置,其中T:class,可识别
...
…或者如果您想绝对打开任何标识符类型的门:
public interface IRepository<TId, T>
where TId : IEquatable<TId>
where T : class, ICanBeIdentifiable<TId>
公共接口IRepository
哪里TId:IEquatable
其中T:类,可识别
主要缺点是您的域对象必须实现整个新接口,但这是值得的。您可以添加额外的接口,它将推动每个实体都具有Id属性
public interface IEntity
{
int Id { get; set; }
}
public interface IRepository<T> where T : class, IEntity
{
}
公共接口的可扩展性
{
int Id{get;set;}
}
公共接口Iposition,其中T:class,icity
{
}
您可以添加额外的接口,该接口将推动每个实体具有Id属性
public interface IEntity
{
int Id { get; set; }
}
public interface IRepository<T> where T : class, IEntity
{
}
公共接口的可扩展性
{
int Id{get;set;}
}
公共接口Iposition,其中T:class,icity
{
}