繁体   English   中英

在C#中收到错误“使用未分配的局部变量”

[英]Getting error “Use of unassigned local variable” in C#

我对编程很陌生,所以如果这是一个简单的解决方法,请原谅我。 关于我的字符串变量“ city”,我一直收到错误消息“使用未分配的局部变量”。 令我感到困惑的是,我还有一个名为“ centreName”的字符串变量,即使它也没有初始化,它也不会出现相同的错误。

该程序的目的是让用户输入科学中心及其所在城市的名称数据。我尝试将“ city”变量初始化为string city = nullstring city = "" ,但是当我运行该程序,输出将显示空白,而不是用户输入的内容。 我的“ centreName”变量不是这种情况。

我将包括我正在使用的两个类的编码。 请忽略我的方法,因为我尚未对其进行调整以适合此程序。 它们是我以前用于某些方法的较旧方法,因此此处不应用编码。

这是我收到错误的类:

class ScienceCentreApp
{
    static void Main(string[] args)
    {
        string centreName;
        string city;
        decimal ticketPrice = 0;
        int visitorCnt;
        string[] dArray = new String[5];
        int[] adultVisitors = new int[5];
        decimal[] totalRevenue = new decimal[5];
        char enterMoreData = 'Y';
        ScienceCentreVisitation scv;


        do
        {
            visitorCnt = GetData(out centreName, city, ticketPrice, dArray, adultVisitors, totalRevenue);
            scv = new ScienceCentreVisitation(centreName, city, ticketPrice, dArray, adultVisitors, totalRevenue);
            Console.Clear();
            Console.WriteLine(scv);

            Console.Write("\n\n\n\nDo you want to enter more data - " +
                          "(Enter y or n)? ");
            if (char.TryParse(Console.ReadLine(), out enterMoreData) == false)
                Console.WriteLine("Invalid data entered - " +
                                    "No recorded for your respones");
        } while (enterMoreData == 'y' || enterMoreData == 'y');

        Console.ReadKey();
    }

    public static int GetData(out string centreName, string city, decimal ticketPrice, string[] dArray, int[] adultVisitors, decimal[] totalRevenue)
    {
        int i,
            loopCnt;

        Console.Clear();
        Console.Write("Name of Centre: ");
        centreName = Console.ReadLine();
        Console.Write("City: ");
        city = Console.ReadLine();
        Console.Write("Ticket Price: ");
        string inValue = Console.ReadLine();
        ticketPrice = Convert.ToDecimal(inValue);
        Console.Write("How many records for {0}? ", centreName);
        string inValue1 = Console.ReadLine();
        if (int.TryParse(inValue1, out loopCnt) == false)
            Console.WriteLine("Invalid data entered - " +
                                "0 recorded for number of records");
        for (i = 0; i < loopCnt; i++)
        {
            Console.Write("\nDate (mm/dd/yyyy): ");
            dArray[i] = Console.ReadLine();
            if (dArray[i] == "")
            {
                Console.WriteLine("No date entered - " +
                                    "Unknown recorded for visits");
                dArray[i] = "Unknown";
            }
            Console.Write("Number of One-Day Adult Visitors: ");
            inValue1 = Console.ReadLine();
            if (int.TryParse(inValue1, out adultVisitors[i]) == false)
                Console.WriteLine("Invalid data entered - " +
                                    "0 recorded for adults visited");
        }
        return i;
    }
}

}

这是第一个正在调用的另一个类:

class ScienceCentreVisitation
{
    private string centreName;
    private string city;
    private decimal ticketPrice;
    private string[] visitDate;
    private int[] adultVisitors;
    private decimal[] totalRevenue;


    //constructors
    public ScienceCentreVisitation()
    {

    }

    public ScienceCentreVisitation(string cent)
    {
        centreName = cent;
    }

    public ScienceCentreVisitation(string cent, string cit, decimal price, string[] date, int[] visit, decimal[] rev)
    {
        visitDate = new string[date.Length];
        adultVisitors = new int[visit.Length];
        totalRevenue = new decimal[rev.Length];
        Array.Copy(date, 0, visitDate, 0, date.Length);
        Array.Copy(visit, 0, adultVisitors, 0, adultVisitors.Length);
        Array.Copy(rev, 0, totalRevenue, 0, rev.Length);
        centreName = cent;
        city = cit;
        ticketPrice = price;
    }

    //properties
    public string CentreName
    {
        get
        {
            return centreName;
        }
        set
        {
            centreName = value;
        }
    }

    public string City
    {
        get
        {
            return city;
        }
        set
        {
            city = value;
        }
    }

    public decimal TicketPrice
    {
        get
        {
            return ticketPrice;
        }
        set
        {
            ticketPrice = value;
        }
    }

    public string[] VisitDate
    {
        get
        {
            return visitDate;
        }
        set
        {
            visitDate = value;
        }
    }

    public int[] AdultVisitors
    {
        get
        {
            return adultVisitors;
        }
        set
        {
            adultVisitors = value;
        }
    }

    public decimal[] TotalRevenue
    {
        get
        {
            return totalRevenue;
        }
        set
        {
            totalRevenue = value;
        }
    }

    //methods
    public decimal CalculateTotalRevenue()
    {
        decimal totalRev;

        int cntOfValidEntries;
        int total = 0;
        foreach (int c in adultVisitors)
            total += c;
        cntOfValidEntries = TestForZeros();
        totalRev = (decimal)total / cntOfValidEntries;
        return totalRev;
    }

    public int TestForZeros()
    {
        int numberOfTrueVisits = 0;
        foreach (int cnt in adultVisitors)
            if (cnt != 0)
                numberOfTrueVisits++;
        return numberOfTrueVisits;
    }

    public int GetIndexOfLeastVisited()
    {
        int minVisIndex = 0;

        for (int i = 1; i < adultVisitors.Length; i++)
            if (adultVisitors[i] > adultVisitors[minVisIndex])
                minVisIndex = i;
        return minVisIndex;
    }

    public int GetLeastVisited()
    {
        return adultVisitors[GetIndexOfLeastVisited()];
    }

    public string GetDateWithLeastVisited()
    {
        return visitDate[GetIndexOfLeastVisited()];
    }

    public int GetIndexOfMostRevenue()
    {
        int maxRevIndex = 0;

        for (int i = 1; i < totalRevenue.Length; i++)
            if (totalRevenue[i] > totalRevenue[maxRevIndex])
                maxRevIndex = i;
        return maxRevIndex;
    }

    public decimal GetMostRevenue()
    {
        return totalRevenue[GetIndexOfMostRevenue()];
    }

    public string GetDateWithMostRevenue()
    {
        return visitDate[GetIndexOfMostRevenue()];
    }

    public override string ToString()
    {
        return "Name of Centre: " + centreName +
               "\nCity: " + city +
                "\nDate of Least One-Day Adult Visitors:\t\t" + GetDateWithLeastVisited() +
                "\nNumber of Least One-Day Adult Visitors: \t\t" + GetLeastVisited() +
                "\nDate of Most Total Revenue Collected:\t\t" + GetDateWithMostRevenue() +
                "\nHighest Total Revenue Collected:\t\t" + GetMostRevenue();
    }
}

}

提前致谢!

centreNamecity之间的区别在于, centreName用作out参数。 这意味着您可以使用未初始化的变量来调用方法,因为可以确保在方法内部为变量分配一个值。

在您的情况下,在GetDatacentreNamecity都分配了值,因此您可以安全地将string city替换为out string city

centerName被声明为out参数(意味着当您离开方法的作用域时,它将保留您在方法内为其分配的最后一个值),因此将通过get数据对其进行初始化。 其余变量未通过get data调用设置,因为它们不是out参数。

在这一点上,C#通常认为out参数是不好的做法(我不会说其他语言)。 大多数情况下,它们掩盖了该方法的用途,在调用该方法(或错误地对其进行初始化)之后,很容易意外覆盖out参数之一的值。 不用使用out参数,而是创建一个包装数据的对象并返回它而不是int。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM