为什么此运行时动态绑定失败?

afe*_*gin 5 c# dynamic

为什么以下测试失败?

[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
    }
}
Run Code Online (Sandbox Code Playgroud)

出现以下错误:

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>)'
has some invalid arguments

绑定器是否应该足够智能以匹配list其底层类型,List<int>从而成功绑定到该GetTotal方法?

Guf*_*ffa 5

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

动态调用是根据您使用的变量的类型确定的,而不是它指向的对象的实际类型.该方法Total需要一个List<int>,而不是一个IEnumerable.

  • 我的印象是动态调用会尝试动态解析参数和方法。我猜不会。当我将调用更改为 *return listTotaller.Total((dynamic)list).ToString()* 时,它起作用了。 (2认同)