C# 具体类中的NHibernate抽象存储库ISession属性
我不知道如何问我的问题,所以我将写几行代码 我有一个抽象基类AbstractRepository,如下所示:C# 具体类中的NHibernate抽象存储库ISession属性,c#,nhibernate,fluent-nhibernate,C#,Nhibernate,Fluent Nhibernate,我不知道如何问我的问题,所以我将写几行代码 我有一个抽象基类AbstractRepository,如下所示: public abstract class AbstractRepository : IGenericRepository { protected ISession Session { get { return Startup.SessionFactor
public abstract class AbstractRepository : IGenericRepository
{
protected ISession Session
{
get
{
return Startup.SessionFactory.GetCurrentSession();
}
}
//More code left out for clarity
}
实现抽象类AbstractRepository的具体类:
public class AccommodationRepository : AbstractRepository
{
// Allow the Session property to be returned from the base class.
public ISession Session => base.Session;
// Which I understand to be the same as the line below:
// public ISession session { get { return base.Session; } }
public async Task<EPICCard> GetByCardNumber(long epicCardId)
{
var session = Session;
CancellationTokenSource token = new CancellationTokenSource();
//Do stuff - not important for now.
return theQueryTask.Result;
}
}
公共类存储库:AbstractRepository
{
//允许从基类返回会话属性。
公共会话=>base.Session;
//据我所知,这与以下内容相同:
//公共ISession会话{get{return base.session;}
公共异步任务GetByCardNumber(长epicCardId)
{
var会话=会话;
CancellationTokenSource令牌=新的CancellationTokenSource();
//做一些事情——现在不重要。
返回querytask.Result;
}
}
Re Sharper建议对生产线进行以下更改:
公共会话=>base.Session
到
public new ISession Session=>base.Session
我应该使用哪一个?为什么
也许有人能解释一下其中一个的原因吗?不确定这是否是缺乏对
创建“新”会话的理由是什么?除非方法是
抽象的或虚拟的
,否则无法重写该方法,因此,通过执行以下操作:
public ISession Session => base.Session;
您正在隐藏基本实现,而不是覆盖它
这会导致根据引用而不是实例选择属性的get
实现
在您的具体示例中,这没有什么区别,但是,以下是一个示例:
public class AccommodationRepository : AbstractRepository
{
public ISession Session => new SomeOtherSession();
void SomeMethod()
{
AbstractRepository thisAsAbstract = this;
object.ReferenceEquals(this.Session, thisAsAbstract.Session); // false
}
}
这是因为thisabstract.Session
使用了Session
的基本实现,因为它只被隐藏了
ReSharper的建议(使用new
关键字)只是明确表示方法隐藏是有意的,而不是偶然的,就像在您的案例中那样(因为您正在更改访问修饰符)。简洁且呈现良好的解释Cudos。我不完全理解“这会导致根据引用而不是实例选择属性的get实现”的含义。我仍在仔细研究它。