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 方法中,如果我将 InterfaceB 替换为 InterfaceA,则代码将毫无错误地执行。IE InterfaceA interfaceA = classB;
为什么会出现这种情况?