为什么这个C#代码没有编译?
public static Dictionary<short,MemoryBuffer> GetBulkCustom(int bufferId,int startSecond,out int chunksize,out int bardatetime) { //const string _functionName = "GetNextBulkWatchData"; UserSeriesCard currentCard = GetUserSeriesCard(bufferId); Dictionary<short,MemoryBuffer> result = null; while (currentCard.CurrentSecond <= startSecond) result = GetBulk(bufferId,out chunksize,out bardatetime); if (result == null) { result = currentCard.UserBuffer; chunksize = currentCard.ChunkSize; bardatetime = currentCard.CurrentBarDateTime; } return result; }
错误:
The out parameter 'bardatetime' must be assigned to before control leaves the current method The out parameter 'chunksize' must be assigned to before control leaves the current method
我想不出bardatetime和chunksize最终会被取消分配的情况.
编辑.我通过将代码调整为逻辑等效的代码来修复此错误.老实说,我想避免多重分配.
public static Dictionary<short,out int bardatetime ) { const string _functionName = "GetNextBulkWatchData"; UserSeriesCard currentCard = GetUserSeriesCard(bufferId); Dictionary<short,MemoryBuffer> result = null; chunksize = currentCard.ChunkSize; bardatetime = currentCard.CurrentBarDateTime; while (currentCard.CurrentSecond <= startSecond) result = GetBulk(bufferId,out bardatetime); if (result == null) result = currentCard.UserBuffer; return result; }
解决方法
如果从未输入while循环和“if语句”主体,则不分配out参数.
从逻辑上讲,您可能知道始终会输入这些代码路径.编译器不知道这一点.编译器认为可以输入或跳过具有非常数条件的每个“if”和“while”.
在这种情况下,编译器可以进行更复杂的流分析.分析是“在’if’之前,结果为null或非null;如果为null,则’if’主体分配out参数.如果它不为null,那么唯一可能发生的方法是’如果’ ‘body指定了out参数,因此out参数被赋值.“
这种分析水平当然是可能的,但规范中描述的现有流量分析算法具有一些很好的特性,即它快速,易于理解,易于实现,通常是准确的,并且只给出误报,而不是假阴性.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。