在下面这段代码的原始版本中,我(懒惰地)使用了var
,结果在代码的完全不同部分出现了奇怪的运行时异常。将“var”更改为“int”可以解决运行时异常,但我还是不能完全理解为什么会出现这种情况。我将代码简化为以下示例:
public class Program
{
private static List<string> Test(string i) { return new List<string> {i}; }
private static dynamic GetD() { return 1; }
public static void Main()
{
int value1 = GetD(); // <-- int
var result1 = Test("Value " + value1);
// No problem, prints "Value 1", First() on List<string> works ok.
Console.WriteLine(result1.First());
var value2 = GetD(); // <-- var
var result2 = Test("Value " + value2);
// The below line gives RuntimeBinderException
// 'System.Collections.Generic.List<string>' does not contain a
// definition for 'First'
Console.WriteLine(result2.First());
}
}
我看到"var"的类型是动态的而不是int,但为什么这个类型会传播到并影响调用
Test()
的返回值的行为呢?编辑:也许我应该澄清我的问题;我可以看到
dynamic
传播到result2
,但我不明白为什么当IDE明确指示调用List<string> Test(string)
方法时,它仍然将返回值推断为动态。难道这是IDE比编译器更聪明的情况吗?