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——太快了!谢谢你的回答——这正是我所期望的。:)哇-太快了!谢谢你的回答——这正是我所期望的。:)