[英]Generic function getting a generic parameter
这可能是一些愚蠢的疏忽,但在这里:
public class Entity<TId> where TId : IEquatable<TId>
{
public virtual TId Id { get; private set; }
}
public class Client : Entity<Guid> { }
public class State : Entity<short> { }
public class Helper
{
protected IList<Client> clients;
protected IList<State> states;
//Works
public T Get<T>()
{
return default(T);
}
public T Get<T>(Guid id) where T : Entity<Guid>
{
return default(T);
}
public T Get<T>(short id) where T : Entity<short>
{
return default(T);
}
}
我怎么写我将使用这两个类的Get函数? 还有其他从Entity继承的东西?
我只是希望我不会得到太多的downvotes。 :(
编辑
这是它将被使用的地方。 所以它不仅仅是两个班级。 但基本上我模型上的所有类。
//What should I declare here?
{
TEntity result = default(TEntity);
try
{
using (var tx = session.BeginTransaction())
{
result = session.Query<TEntity>().Where(e => e.Id == Id).FirstOrDefault();
}
return result;
}
catch (Exception ex)
{
throw;
}
}
使用SWeko提供的解决方案
public TEntity Get<TEntity, TId>(TId Id)
where TEntity : Entity<TId>
where TId : IEquatable<TId>
{
try
{
TEntity result = default(TEntity);
using (var tx = statefullSession.BeginTransaction())
{
result = statefullSession.Query<TEntity>().Where(e => e.Id.Equals(Id)).FirstOrDefault();
}
return result;
}
catch (Exception ex)
{
throw;
}
}
如果问题只是放在Get
方法的where
子句中,你可以这样做:
public TEntity Get<TEntity, TId> (TId id) where TEntity : Entity<TId>
where TId : IEquatable<TId>
{
.....
}
我不认为需要通用的Get
方法,因为您希望从预定义的两个列表中返回事先已知类型的对象(客户端,状态)。
public class Helper
{
protected IList<Client> clients;
protected IList<State> states;
public Client GetClient(Guid id)
{
return clients.Where(c => c.Id == id);
}
public State GetState(short id)
{
return states.Where(s => s.Id == id);
}
}
考虑使用词典来表示速度,其中id用作键。
或者,您可以将两个公共Get方法基于一个私有通用Get方法
private TEntity Get<TEntity,TId>(IList<TEntity> list, TId id)
{
return list.Where(item => item.Id == id);
}
public Client GetClient(Guid id)
{
return Get(clients, id);
}
public State GetState(short id)
{
return Get(states, id);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.