gpt4 book ai didi

c# - 从 Inherited 接口(interface)调用方法时传递动态参数会抛出 RuntimeBinderException

转载 作者:太空狗 更新时间:2023-10-29 20:24:59 26 4
gpt4 key购买 nike

经过一些重构后遇到一个有趣的运行时问题,并确定为以下情况。

当将动态对象的属性传递给从父接口(interface)继承的接口(interface)上的方法时,运行时绑定(bind)程序无法找到该方法。

这里有一个测试来证明失败和成功(当直接在父接口(interface)类型上调用方法时)

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, dynObject.Foo, false, exceptionMessage);
}
}
}

测试 #1 失败:Assert.AreEqual 失败。预期:<(空)>。实际的:。 “Test.Utility.IInheritEcho”不包含“EchoString”的定义

测试 #2 成功。

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

我知道我可以通过在传递参数时转换参数或在传递参数之前将它们分配给变量来解决这个问题。我只是好奇继承接口(interface)导致 RuntimeBinder 失败的原因。 .

最佳答案

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

关于c# - 从 Inherited 接口(interface)调用方法时传递动态参数会抛出 RuntimeBinderException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10531575/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com