具体 Class 中的 NHibernate 抽象存储库 ISession 属性

NHibernate Abstract Repository ISession Property in Concrete Class

我不知道怎么问我的问题,所以我会写几行代码...

我有一个抽象基础 class AbstractRepository 像这样:

 public abstract class AbstractRepository : IGenericRepository
    {       
        protected ISession Session
        {
            get
            {
                return Startup.SessionFactory.GetCurrentSession();
            }            
        }
          
        //More code left out for clarity
}

实现抽象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 建议对该行进行以下更改:

public ISession Session => base.Session;

public new ISession Session => base.Session;

我应该使用哪一个,为什么?

有人可以解释其中一个优于另一个的原因吗?不知道是不是对

的理解不够
  1. 糟糕,
  2. NHibernate 管道
  3. 或者两者兼而有之?

创建 'new' ISession 的原因是什么?

除非方法是 abstractvirtual,否则您不能重写方法,因此这样做:

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
    }
}

发生这种情况是因为 thisAsAbstract.Session 使用了 Session 的基本实现,因为它只是被隐藏了。

ReSharper 的建议(使用 new 关键字)只是明确表明方法隐藏是有意的而不是偶然的,就像你的情况一样(因为你正在更改访问修饰符).