为什么在使用条件运算符时需要显式的ToString()?
我有以下代码来组成一个简单的SOAP Post表单数据值:
var postParameters = new Dictionary { { "someNumber", "100" }, { "someString", "Hello World" } }; var resultWhenNotInConditional = postParameters .Keys .Zip(postParameters.Values, (key, value) => string.Format("{0}={1}", key, value)) .Aggregate(null, (prev, next) => (prev != null) ? string.Format("{0}&{1}", prev, next) : next);
它按设计工作,即
resultWhenNotInConditional = "someNumber=100&someString=Hello World"
但是,当我将它包装在条件运算符中进行空检查时,如下所示:
var resultWhenInConditional = (postParameters != null) ? postParameters .Keys .Zip(postParameters.Values, (key, value) => string.Format("{0}={1}", key, value)) .Aggregate(null, (prev, next) => (prev != null) ? string.Format("{0}&{1}", prev, next) : next) : string.Empty;
resultWhenInConditional
似乎总是为null,无论postParameters
是设置为null还是设置为有效的Dictionary
。 (将var
更改为显式string
也无效)。
我可以解决这个问题的唯一方法是在Aggregate
之后添加ToString()
,即:
var resultWhenInConditional = (postParameters != null) ? postParameters .Keys .Zip(postParameters.Values, (key, value) => string.Format("{0}={1}", key, value)) .Aggregate(null, (prev, next) => (prev != null) ? string.Format("{0}&{1}", prev, next) : next) .ToString() // R# warns this is redundant : string.Empty;
所以我的问题是,为什么我需要在条件运算符内添加额外的.ToString()
?
- Microsoft Visual Studio Professional 2010版本10.0.40219.1 SP1Rel
- Microsoft .NET Framework版本4.0.30319 SP1Rel
编辑
感谢您的反馈!
要确认这只是一种偏差 – VS IDE将变量报告为NULL(在鼠标hover+立即窗口中),但仅在使用R#NUnit测试运行器单独调试unit testing时。 在控制台App下进行调试在IDE中正确报告值。
即只有在Resharper NUnit TestRunner下进行调试时才会发生这种情况。
一旦变量被其他代码访问(例如Assert
/ Console.Writeline
等),很明显该值实际上不是null。
我已经向GitHub添加了一个控制台应用程序和截图
没有任何unit testing实际上失败,即该值实际上不是null 🙂
- R#7.1.3 C#Edition(2224)
- NUnit 2.6.1.12217
要确认这只是一种偏差 – VS IDE将变量报告为NULL(在鼠标hover+立即窗口中),但仅在使用R#NUnit测试运行器单独调试unit testing时。 在控制台App下进行调试在IDE中正确报告值。
即只有在Resharper NUnit TestRunner下进行调试时才会发生这种情况。
一旦变量被其他代码访问(例如Assert
/ Console.Writeline
等),很明显该值实际上不是null。
我已经向GitHub添加了一个控制台应用程序和截图
没有任何unit testing实际上失败,即该值实际上不是null 🙂
- R#7.1.3 C#Edition(2224)
- NUnit 2.6.1.12217