I have an Interface as below:
public interface IRepository<T> where T : class
{
T is type of my entities.
In this interface I have some methods which will use Entity's Id property. So, How can I guarantee that, the Entity has Id property when some body wants to implement this interface?
答案 0 :(得分:3)
救援的接口!
按如下方式定义界面:
// 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>
主要缺点是您的域对象必须实现全新的界面,但值得付出努力。
答案 1 :(得分:1)
您可以添加其他界面,这将推动每个实体拥有Id属性
public interface IEntity
{
int Id { get; set; }
}
public interface IRepository<T> where T : class, IEntity
{
}