C# 接口继承(基础)
为什么以下会产生编译器错误:
public interface OwnSession : ISession { }
[...]
OwnSession s = SessionFactory.OpenSession(); // compiler error (in german unfortunately)
[...]
“SessionFactory”在“OpenSession()”上返回“ISession”(NHibernate)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你应该转换结果:
如果 OpenSession() 返回一个 ISession 类型,它可以是任何实现 ISession 的类型,所以你必须告诉编译器你期望一个 OwnSession 类型(只有当你确定它会当然返回)
另一方面,您可以将变量声明为 ISession,并继续使用它。除非您想使用 ISession 接口规范中不可用的 OwnSession 类型的方法或属性。
You should cast the result:
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.
返回的对象只是“ISession”,而不是“OwnSession”(顺便说一句。您应该在其前面加上 I: IOwnSession)。想象一下,你有一个返回汉堡的函数,你不能将其转换为芝士汉堡,因为它可能不是一个......
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...
我猜是因为 OwnSession 可能是一个比 ISession 更大/不同的接口?
想象一下,如果 OwnSession 继承自 ISession 但还添加了另一个方法签名。那么 SessionFactory.OpenSession 方法返回的 ISession 将与 OwnSession 定义的协定不匹配(或者可以,但不一定,具体取决于返回的实际具体类型。)编译器不知道)
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)
SessionFactory.OpenSession 调用将返回一个实现 ISession 接口的对象,但您的 OwnInterface 更具体。强制转换可能是解决这个问题的一种方法,或者直接使用 ISession...
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...