C# 接口继承(基础)

发布于 2024-08-25 02:09:45 字数 259 浏览 5 评论 0原文

为什么以下会产生编译器错误:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

妄想挽回 2024-09-01 02:09:45

你应该转换结果:

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

如果 OpenSession() 返回一个 ISession 类型,它可以是任何实现 ISession 的类型,所以你必须告诉编译器你期望一个 OwnSession 类型(只有当你确定它会当然返回)

另一方面,您可以将变量声明为 ISession,并继续使用它。除非您想使用 ISession 接口规范中不可用的 OwnSession 类型的方法或属性。

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.

偏闹i 2024-09-01 02:09:45

返回的对象只是“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...

怪异←思 2024-09-01 02:09:45

我猜是因为 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)

暗地喜欢 2024-09-01 02:09:45

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文