加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:00:53 所属栏目:百科 来源:网络整理
导读:在进行一些重构后进入一个有趣的运行时问题,并将其归结为以下情况. 将属性从动态对象传递到已从父接口继承的接口上的方法时,运行时绑定程序无法找到该方法. 这是一个测试,用于演示失败和成功(直接在父接口类型上调用方法) using System.Dynamic;using Micros
在进行一些重构后进入一个有趣的运行时问题,并将其归结为以下情况.

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读