Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 访问在Hiarachy类中多次实现的接口_C#_Interface - Fatal编程技术网

C# 访问在Hiarachy类中多次实现的接口

C# 访问在Hiarachy类中多次实现的接口,c#,interface,C#,Interface,如果我们有以下示例应用程序: 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实现? 例如:

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

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!"

注意,这不是真实世界的问题,而是一个普遍的疑问

不,不是。至少在正常情况下不是这样——你可以通过反射来实现

基本上,通过重新实现
ITest
B
意味着它完全负责
ITest.Test
在任何
B
类型的对象中进行测试,并且你甚至不能从
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”。但这很可怕——我必须不顾一切地去做…

不,不是。至少在正常情况下不是这样——你可以通过反射来实现

基本上,通过重新实现
ITest
B
意味着它完全负责
ITest.Test
在任何
B
类型的对象中进行测试,并且你甚至不能从
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”。不过,这太可怕了——我不得不不顾一切地去做……

Woah——太快了!谢谢你的回答——这正是我所期望的。:)哇-太快了!谢谢你的回答——这正是我所期望的。:)