开发者

C# Interface Inheritance (Basics)

Why does the fo开发者_Python百科llowing 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...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜