using System;
namespace DynamicIssues
{
public interface InterfaceA
{
void InterfaceAMethod(dynamic x);
}
public interface InterfaceB : InterfaceA
{
}
public abstract class ClassA : InterfaceA
{
public virtual void InterfaceAMethod(dynamic x)
{
Console.WriteLine("A: " + x.ToString());
}
}
public class ClassB : ClassA, InterfaceB
{
public override void InterfaceAMethod(dynamic x)
{
Console.WriteLine("B: " + x.ToString());
}
}
public class ToStringer
{
public string Value = "StringVal";
public override string ToString()
{
return Value;
}
}
class Program
{
static void Main(string[] args)
{
ClassB classB = new ClassB();
InterfaceB interfaceB = classB;
dynamic x = new ToStringer(); //Using "var", application works fine.
classB.InterfaceAMethod(x); //"B: StringVal" is printed, as expected
interfaceB.InterfaceAMethod(x); //Throws runtime binder exception with message "'DynamicIssues.InterfaceB' does not contain a definition for 'InterfaceAMethod'."
}
}
}
此应用程序编译良好。但是,当 x 的类型声明为动态(而不是仅使用 var(时,将引发运行时绑定器异常。
此外,在 main 方法中,如果我将接口 B 替换为接口 A,代码将执行而不会出错。即接口A接口A = B类;
为什么会这样?
因为当接口(B(扩展接口(A(时,接口(B(仍然不拥有"InterfaceAMethod",所以类B只实现了InterfaceA的方法InterfaceAMethod。