0
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;

为什么会出现这种情况?

4

1 回答 1

-1

因为当interface(B)扩展interface(A)时,interface(B)还没有拥有“InterfaceAMethod”,所以classB只是实现了InterfaceA的方法InterfaceAMethod。

于 2017-04-10T03:00:34.583 回答