微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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上记录的错误

原文地址:https://www.jb51.cc/csharp/100314.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐