访问类层次结构中多次实现的接口

发布于 2024-12-12 01:57:53 字数 489 浏览 0 评论 0原文

如果我们有以下示例应用程序:

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

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

发布评论

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

评论(1

反差帅 2024-12-19 01:57:53

不,不是。至少通常不会——你可以通过反思来做到这一点。

基本上,通过重新实现 ITestB 表示它完全负责在 类型的任何对象中实现 ITest.Test B - 你甚至不能从 B 中调用它,如果你以通常的方式重写,你通常可以调用它。

编辑:我刚刚证明(以一种黑客的方式)你可以用反射来调用它:

using System;

public interface IFoo
{
    void Foo();
}

public class Base : IFoo
{
    void IFoo.Foo()
    {
        Console.WriteLine("Base");
    }
}

public class Derived : Base, IFoo
{
    void IFoo.Foo()
    {
        Console.WriteLine("Derived");
    }
}

class Test
{
    static void Main()
    {
        var map = typeof(Base).GetInterfaceMap(typeof(IFoo));            
        var method = map.TargetMethods[0]; // There's only one method :)
        method.Invoke(foo, null);
    }
}

这会打印出“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 of ITest.Test within any object of type B - and you can't even call it from within B 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:

using System;

public interface IFoo
{
    void Foo();
}

public class Base : IFoo
{
    void IFoo.Foo()
    {
        Console.WriteLine("Base");
    }
}

public class Derived : Base, IFoo
{
    void IFoo.Foo()
    {
        Console.WriteLine("Derived");
    }
}

class Test
{
    static void Main()
    {
        var map = typeof(Base).GetInterfaceMap(typeof(IFoo));            
        var method = map.TargetMethods[0]; // There's only one method :)
        method.Invoke(foo, null);
    }
}

This prints out "Base". It's pretty horrible though - I'd have to be desperate to do it...

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