c# – 从Inherited接口调用Method时,传递动态参数会抛出RuntimeBinderException

在进行一些重构后进入一个有趣的运行时问题,并将其归结为以下情况.

属性从动态对象传递到已从父接口继承的接口上的方法时,运行时绑定程序无法找到该方法.

这是一个测试,用于演示失败和成功(直接在父接口类型上调用方法)

using System.Dynamic;
using Microsoft.CSharp.RuntimeBinder;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Test.Utility
{
    public interface IEcho
    {
        string EchoString(string input);
    }

    public interface IInheritEcho : IEcho
    { }

    public class EchoClass : IInheritEcho
    {
        public string EchoString(string input)
        {
            return input;
        }
    }

    [TestClass]
    public class RuntimeBinderTest
    {
        [TestMethod]
        public void RuntimeBinder_should_work_when_dynamic_parameters_are_passed_to_method_from_inherited_interface()
        {
            //Arrange
            dynamic dynObject = new ExpandoObject();
            dynObject.Foo = "Bar";
            IInheritEcho echomore = new EchoClass();

            string echo = null;
            string exceptionMessage = null;

            //Act
            try
            {
                echo = echomore.EchoString(dynObject.Foo);
            }
            catch (RuntimeBinderException e)
            {
                exceptionMessage = e.Message;
            }

            //Assert
            Assert.AreEqual(echo,dynObject.Foo,false,exceptionMessage);
        }

        [TestMethod]
        public void RuntimeBinder_should_work_when_dynamic_parameters_are_passed_to_method_from_noninherited_interface()
        {
            //Arrange
            dynamic dynObject = new ExpandoObject();
            dynObject.Foo = "Bar";
            IEcho echomore = new EchoClass();

            string echo = null;
            string exceptionMessage = null;

            //Act
            try
            {
                echo = echomore.EchoString(dynObject.Foo);
            }
            catch (RuntimeBinderException e)
            {
                exceptionMessage = e.Message;
            }

            //Assert
            Assert.AreEqual(echo,exceptionMessage);
        }
    }
}

测试#1失败:
Assert.AreEqual失败.预期:其中(空)取代.实际:. ‘Test.Utility.IInheritEcho’不包含’EchoString’的定义

测试#2成功.

我的问题是我的第一次测试应该通过的假设是否正确,或者框架中有一个根本原因,它不是吗?

我知道我可以通过在传入参数时转换参数来解决问题,或者在传递它们之前将它们分配给变量.我更好奇的是继承接口导致RuntimeBinder失败的原因…

解决方法

您的情况是 Microsoft Connect上记录的错误

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...