访问类层次结构中多次实现的接口
如果我们有以下示例应用程序:
interface ITest
{
string Test { get; }
}
class A : ITest
{
string ITest.Test { get { return "Test from A!"; } }
}
class B : A, ITest
{
string ITest.Test { get { return "Test from B!"; } }
}
给定 B 的实例,是否可以访问 A 的 ITest 实现? 例如:
B b = new B();
ITest test = b;
string value = test.Test; // "Test from B!"
A a = b;
test = a;
value = test.Test; // Still "Test from B!"
注意,这不是现实世界的问题,而是一个普遍的问题。
If we have the following sample application:
interface ITest
{
string Test { get; }
}
class A : ITest
{
string ITest.Test { get { return "Test from A!"; } }
}
class B : A, ITest
{
string ITest.Test { get { return "Test from B!"; } }
}
Given an instance of B, is it possible to access A's implementation of ITest?
For example:
B b = new B();
ITest test = b;
string value = test.Test; // "Test from B!"
A a = b;
test = a;
value = test.Test; // Still "Test from B!"
Note, this is no real world problem but more of a general wondering.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,不是。至少通常不会——你可以通过反思来做到这一点。
基本上,通过重新实现
ITest
,B
表示它完全负责在类型的任何对象中实现
- 你甚至不能从ITest.Test
BB
中调用它,如果你以通常的方式重写,你通常可以调用它。编辑:我刚刚证明(以一种黑客的方式)你可以用反射来调用它:
这会打印出“Base”。但这太可怕了——我必须不顾一切地去做……
No, it's not. At least not normally - it's possible that you could do it with reflection.
Basically, by reimplementing
ITest
,B
is saying that it's taking complete responsibility for the implementation ofITest.Test
within any object of typeB
- and you can't even call it from withinB
which you'd normally be able to if you were overriding in the usual way.EDIT: I've just proved (in a hacky way) that you can call it with reflection:
This prints out "Base". It's pretty horrible though - I'd have to be desperate to do it...