【问题标题】:Use of unassigned variable?使用未分配的变量?
【发布时间】:2014-03-07 11:49:14
【问题描述】:

在声明 paymentstatus 是否为 null 或在“if”语句中具有值时,我收到未分配变量“ps”的错误使用。我在想我已经宣布 ps 但显然我做错了什么。为什么编译器会抱怨这个?

这是上下文中的错误:

public IList<BestsellersReportLine> DailyBestsellersReport()
        {


            OrderStatus os; 
            PaymentStatus? ps; 
            ShippingStatus ss;
            int billingCountryId = 0;
            int recordsToReturn = 999; 
            int orderBy = 1;
            int groupBy = 1;



            int? paymentStatusId = null;
            if (ps.HasValue)
                paymentStatusId = (int)ps.Value;



            // Specifies the time range for sold products/day
            var range = new
            {
                startTimeUtc = DateTime.Today.AddDays(-1),
                endTimeUtc = DateTime.Today.AddSeconds(-1),



                CreatedOnUtc = DateTime.Today.AddDays(-1),

            };




            var query1 = from opv in _opvRepository.Table
                         join o in _orderRepository.Table on opv.OrderId equals o.Id
                         join pv in _productVariantRepository.Table on opv.ProductVariantId equals pv.Id
                         join p in _productRepository.Table on pv.ProductId equals p.Id
                         where (o.CreatedOnUtc >= range.startTimeUtc && o.CreatedOnUtc <= range.endTimeUtc) &&
                         (!paymentStatusId.HasValue || paymentStatusId == o.PaymentStatusId)
                         select opv;
}

谢谢!

【问题讨论】:

    标签: c# asp.net-mvc linq nopcommerce unassigned-variable


    【解决方案1】:

    你已经声明了局部变量,但你还没有赋值。因此,编译器可以帮助您防止此错误。

    PaymentStatus? ps;  
    // ...
    if (ps.HasValue)
    

    所以赋值:

    PaymentStatus? ps = null;  
    // ...
    if (ps.HasValue)
    

    但是,thix 修复了编译器错误,但仍然毫无意义,因为它永远不会有值。也许您想改用方法参数:

    public IList<BestsellersReportLine> DailyBestsellersReport(PaymentStatus? ps)
    {
    

    【讨论】:

    • 我可以按照您的建议将参数放入方法中,但我不想将它们保留在外面。但是,它可以将变量设置为 null。
    【解决方案2】:

    初始化你的ps变量

    PaymentStatus? ps = null; //or something. 
    

    来自Compiler Error CS0165

    C# 编译器不允许使用未初始化的变量。如果 编译器检测到可能没有使用的变量 初始化,它会生成编译器错误 CS0165

    【讨论】:

      【解决方案3】:

      这是一个未赋值的变量,即你没有用一个值初始化它。

      【讨论】:

        【解决方案4】:

        是的,你确实声明了变量。

        但它说“未分配”而不是“未声明”,并且您没有为变量分配任何值。只需将其设置为 null。

        【讨论】:

          【解决方案5】:

          你还没有初始化ps...你需要至少用null值初始化它...

          PaymentStatus? ps = null;
          

          这同样适用于所有其他变量

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-10-04
            • 2013-10-18
            • 2015-11-09
            • 2012-05-18
            • 1970-01-01
            相关资源
            最近更新 更多