C # interface inheritance (basics)

Why the following errors result in a compiler error:

public interface OwnSession : ISession { } [...] OwnSession s = SessionFactory.OpenSession(); // compiler error (in german unfortunately) [...] 

"SessionFactory" returns "ISession" to "OpenSession ()" (NHibernate)

+4
source share
4 answers

I'm going to guess, because OwnSession can be a much larger / different interface than ISession?

Imagine if OwnSession is inherited from ISession, but also adds a different method signature .. then ISession returned by SessionFactory.OpenSession will correspond to the contract defined by OwnSession (or it may, but not necessarily, depending on a specific type, returned ... the compiler does not know this)

+1
source

You must indicate the result:

 OwnSession s = (OwnSession) SessionFactory.OpenSession(); 

If OpenSession () returns an ISession type, that could be all that ISession implements, so you should tell the compiler that you are expecting an OwnSession type (only if you are sure that it will return this, of course)

On the other hand, you can declare your variable as ISession and continue to work with it. If you do not want to use methods or properties from the OwnSession type that are not available in the ISession interface specification.

+10
source

The returned object is only "ISession", it is not "OwnSession" (by the way, you must attach it to I: IOwnSession). Imagine that you have a function that returns a hamburger, you cannot throw it like a cheesburger, because it may not be one ...

+5
source

An SessionFactory.OpenSession call will return an object that implements the ISession interface, but your OwnInterface is more specific. Casting may be the only way out of this or work directly with ISession ...

0
source

Source: https://habr.com/ru/post/1303934/


All Articles