[英]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.