[英]NHibernate Abstract Repository ISession Property in Concrete Class
I am not sure how to ask my question, so I will write a few lines of code...我不知道如何问我的问题,所以我会写几行代码......
I have an abstract base class AbstractRepository like this:我有一个像这样的抽象基础 class AbstractRepository :
public abstract class AbstractRepository : IGenericRepository
{
protected ISession Session
{
get
{
return Startup.SessionFactory.GetCurrentSession();
}
}
//More code left out for clarity
}
A concrete class that implements the abstract class, AbstractRepository:实现抽象 class 的具体 class,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;
}
}
Re-Sharper suggests the following change for the line: Re-Sharper 建议对该行进行以下更改:
public ISession Session => base.Session;
公共 ISession Session => base.Session;
TO至
public new ISession Session => base.Session;
公共新ISession Session => base.Session;
Which one would should I use and why?我应该使用哪一个,为什么?
Can someone perhaps explain the reasoning for one over the other?有人可以解释其中一个的原因吗? Not sure if this is a lack of understanding of
不知道是不是理解不够
What is the reasoning for creating a 'new' ISession?创建“新”ISession 的原因是什么?
You cannot override a method unless it is abstract
or virtual
, so by doing this:你不能覆盖一个方法,除非它是
abstract
或virtual
,所以这样做:
public ISession Session => base.Session;
You are hiding the base implementation rather than overriding it.您正在隐藏基本实现而不是覆盖它。
This causes the property's get
implementation to be selected based on the reference rather than the instance.这会导致基于引用而不是实例来选择属性的
get
实现。
In your specific example this makes little difference, however, here is an example where it would:在您的具体示例中,这几乎没有什么区别,但是,这是一个示例:
public class AccommodationRepository : AbstractRepository
{
public ISession Session => new SomeOtherSession();
void SomeMethod()
{
AbstractRepository thisAsAbstract = this;
object.ReferenceEquals(this.Session, thisAsAbstract.Session); // false
}
}
This happens because thisAsAbstract.Session
uses the base implementation of Session
as it has only been hidden.这是因为
thisAsAbstract.Session
使用了Session
的基本实现,因为它只是被隐藏了。
The suggestion by ReSharper (to use the new
keyword) is simply to make explicit that method hiding was intended rather than accidental, as in your case it seems to be (because you are changing the access modifier). ReSharper 的建议(使用
new
关键字)只是为了明确表明方法隐藏是有意的而不是偶然的,就像您的情况一样(因为您正在更改访问修饰符)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.