删除这个无用的赋值给局部变量c#

时间:2017-12-20 09:55:12

标签: c# lint sonarlint

from docx import Document

def matches_my_condition(line):
    """ Returns true or false if the given line should be added to the document """
    # Which will return true if the word cake appears in the line
    return 'cake' in line

# Prepare document
document = Document()

with open('my_text_file.txt', 'r') as textfile:
    for line in textfile.readlines():
        if matches_my_condition(line):
            document.add_paragraph(line)

document.save('my_cake_file.docx')

使用声纳代码分析时出现警告错误:

  

将此无用的分配移至局部变量var stopFyon = new StopFYON(); IEnumerable<CarOnline> carOnlineData = (IEnumerable<CarOnline>)vehrep.GetCarOnlineDetail(maintainStopFactoryOrderNo.VehicleDetail).Result; if (carOnlineData.Any()) { stopFyon = vehtran.CreateStopFactoryOrderNo(carOnlineData, maintainStopFactoryOrderNo, lastUpdatedBy); } else { stopFyon = vehtran.CreateStopFactoryOrderNo(null, maintainStopFactoryOrderNo, lastUpdatedBy); } return gen.GetResponse((Int16)ResultCode.Success, (Int16)MsgType.Ok, null, vehrep.StopFactoryOrderNo(stopFyon));

4 个答案:

答案 0 :(得分:5)

请勿使用var

StopFYON stopFyon;

警告的原因是你使用默认构造函数初始化变量(理论上这可能是一个非常昂贵的调用,至少它是令人困惑的)。但是在所有分支(ifelse)中都会覆盖此分配。所以它没用。

如果您在stopFyon之前使用if警告也会消失。

答案 1 :(得分:2)

该消息非常简单:

IEnumerable<CarOnline> carOnlineData = (IEnumerable<CarOnline>)vehrep.GetCarOnlineDetail(maintainStopFactoryOrderNo.VehicleDetail).Result;

StopFYON stopFyon;

if (carOnlineData.Any())
    stopFyon = vehtran.CreateStopFactoryOrderNo(carOnlineData, maintainStopFactoryOrderNo, lastUpdatedBy);
else
    stopFyon = vehtran.CreateStopFactoryOrderNo(null, maintainStopFactoryOrderNo, lastUpdatedBy);

第一项任务:

var stopFyon = new StopFYON();

没用,因为另一个分配是在if statement之后执行的。

答案 2 :(得分:1)

当我更改代码StopFYON stopFyon = null而不是var stopFyon = new StopFYON();

时,它正常工作

答案 3 :(得分:1)

只需使用headerComponentParams : { showIcon: true/false/somefunction // show icon in headerComponent base on this param value } 分配类型,就不必在条件块分配实际值时进行初始化。