为什么以下测试失败?
[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方法?
问题是list在GetTotal方法中不是一个List<int>.
动态调用是根据您使用的变量的类型确定的,而不是它指向的对象的实际类型.该方法Total需要一个List<int>,而不是一个IEnumerable.
| 归档时间: |
|
| 查看次数: |
4375 次 |
| 最近记录: |