简体   繁体   中英

C# Interface Inheritance (Basics)

Why does the following produce a compiler error:

public interface OwnSession : ISession { }

[...]
OwnSession s = SessionFactory.OpenSession(); // compiler error (in german unfortunately)
[...]

"SessionFactory" returns a "ISession" on "OpenSession()" (NHibernate)

You should cast the result:

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

If OpenSession() returns an ISession type, it could be anything that implements ISession, so you have to tell the compiler you expected a OwnSession type (only if you are sure it will return that of course)

On the other hand, you could declare your variable as ISession, and continue working with that. Unless you want to use methods or properties from the OwnSession type which are not available in the ISession interface spec.

The returned object is only "ISession" it is not an "OwnSession" (btw. you should prefix it with I: IOwnSession). Imagine you have a function returning a burger, you cannot cast it as a cheesburger because it might not be one...

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

Imagine if OwnSession inherited from ISession but also added another method signature.. then the ISession returned by the SessionFactory.OpenSession method would mot match the contract defined by OwnSession (or it could, but not necessarily, depending on the actual concrete type returned... the compiler doesn't know that)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM