gpt4 book ai didi

c# - 为什么这个运行时动态绑定(bind)会失败?

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

为什么下面的测试会失败?

[TestClass]
public class DynamicTests
{
public class ListOfIntsTotaller
{
public float Total(List<int> list) { return list.Sum(); }
}
public static class TotalFormatter
{
public static string GetTotal(IEnumerable list, dynamic listTotaller)
{
// Get a string representation of a sum
return listTotaller.Total(list).ToString();
}
}
[TestMethod]
public void TestDynamic()
{
var list = new List<int> { 1, 3 };
var totaller = new ListOfIntsTotaller();
Assert.AreEqual("4", totaller.Total(list).ToString()); // passes
Assert.AreEqual("4", TotalFormatter.GetTotal(list, totaller)); // fails
}
}

出现以下错误:

Test method MyTests.DynamicTests.TestDynamic threw exception:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: The best overloaded method match for
'MyTests.DynamicTests.ListOfIntsTotaller.Total(System.Collections.Generic.List<int>)'<br/>
has some invalid arguments

Binder 不应该足够智能以匹配list吗?到其基础类型 List<int>从而成功绑定(bind)到 GetTotal方法?

最佳答案

问题是 listGetTotal方法不是 List<int> .

动态调用取决于您使用的变量类型,而不是它指向的对象的实际类型。方法Total需要 List<int> ,不是 IEnumerable .

关于c# - 为什么这个运行时动态绑定(bind)会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7797207/

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