2015-04-04 70 views
0

我对编程非常陌生,所以请原谅我,如果这是一个简单的修复。对于我的字符串变量“city”,我始终得到一个错误“使用未分配的局部变量”。令我困惑的是,我也有一个名为“centreName”的字符串变量,即使它没有被初始化也不会引发相同的错误。在C#中出现错误“使用未分配的局部变量”

这个程序的重点是让用户输入科学中心的名称和它所在的城市的数据。我尝试初始化“城市”变量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(); 
    } 
} 

}

提前致谢!

+0

它永远不会被分配一个值 – Plutonix 2015-04-04 15:47:29

+0

局部变量在使用前必须完全初始化。 – chomba 2015-04-04 15:48:18

+0

'centreName'不会引发错误,因为您不是试图使用它的值,而是将它用作'out'变量。 – Banana 2015-04-04 15:48:38

回答

3

centreNamecity之间的差异是centreName被用作out参数。这意味着你可以用一个未初始化的变量调用该方法,因为它可以保证该变量在方法内部被分配一个值。

在你的情况下,两个centreNamecityGetData为指定的值,这样你就可以放心地out string city取代string city

+0

非常感谢!你不知道我唠叨了多久,然后用Google找出了这个问题。 – Feniks 2015-04-04 15:58:53

0

centreName被声明为一个out参数(意味着当你离开方法的作用域时,它将保留你在方法内赋给它的最后一个值),所以它被get数据初始化。其余的变量不会被get数据调用设置,因为它们不是out参数。

在这一点上,out参数在C#中通常被认为是不好的做法(我不能说其他语言)。他们大多模糊了方法的用途,并且在方法被调用后(或者错误地初始化它)很容易意外地覆盖了其中一个输出参数的值。不要使用out参数,而是创建一个包装数据的对象,并返回该数据而不是int。

+0

我很欣赏这个建议,但这是一份学校作业,而且这是我迄今为止所学的知识。不过,我会尽量避免在自己的项目上工作。谢谢你的提示。 – Feniks 2015-04-04 15:59:45

+1

只要记住'out'参数确实有它们的位置。在这种情况下,我同意这个答案:返回一个自定义类型可能会更好,但对于另一个例子,我非常喜欢将'T XXX()'与'bool TryXXX(out T result)'配对的模式。例如'int.TryParse','Dictionary.TryGetValue'。 – hvd 2015-04-04 16:02:34

+0

@ hvd我完全同意,当你的失败行为必须被处理,但是是预期的,所以不应该抛出异常时,该模式可能非常有用。 – 2015-04-04 16:03:46

相关问题