C#.Net 4.5, Interface Missing Definition for Method with Dynamic Parameter

时间:2017-04-10 02:29:06

标签: c# dynamic .net-4.5 missingmethodexception

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'."
        }
    }
}

This application compiles fine. However, when the type of x is declared as dynamic (as opposed to just using var) a runtime binder exception is thrown.

Also, in the main method if I replace the InterfaceB with InterfaceA the code will execute without error. I.E InterfaceA interfaceA = classB;

Why does this occur?

1 个答案:

答案 0 :(得分:-1)

because when interface(B) extends interface(A),interface(B) still not own the the "InterfaceAMethod", so classB just implement InterfaceA's method InterfaceAMethod.

相关问题