2017-07-14 66 views
-2

下面的代碼沒有返回任何值。我試圖在平衡值低於0美元的地方打印客戶名稱和餘額。我相信我的財產可能並不正確。我是面向對象編程和LINQ的新手。任何幫助將是可觀的。遇到C#屬性,構造函數和LINQ問題

namespace LinqExample 
{ 
    class Customer 
    { 
     private string name, phone, address; 
     private int balance; 
     public string custData; 

     public string Name 
     { 
      get { return name; } 
      set { name = value; } 
     } 

     public string Phone 
     { 
      get { return phone; } 
      set { phone = value; } 
     } 

     public string Address 
     { 
      get { return address; } 
      set { address = value; } 
     } 

     public int Balance 
     { 
      get { return balance; } 
      set { balance = value; } 
     } 

     public Customer(string name, string phone, string address, int balance) 
     { 
      custData = name + phone + address + balance; 
     } 
    } 
} 

namespace LinqExample 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      List<Customer> customers = new List<Customer>(); 

      customers.Add(new Customer("Amit", "123-456-789", "123 Any Road", 25)); 
      customers.Add(new Customer("Ajay", "571-888-1234", "1234 Any Street", 50)); 
      customers.Add(new Customer("John", "707-123-4560", "456 John Street", -10)); 
      customers.Add(new Customer("Ashley", "707-123-8402", "789 Ashley Street", -20)); 

      var overdue = 
       from cust in customers 
       where cust.Balance < 0 
       orderby cust.Balance ascending 
       select new { cust.Name, cust.Balance }; 

      foreach (var cust in overdue) 
      { 
       Console.WriteLine($"Name = {cust.Name}, Balance = {cust.Balance}"); 
      } 

     } 
    } 
} 
+1

你沒有在這些屬性中設置任何值! – Nilay

回答

4

您需要設置成員值:

public Customer(string name, string phone, string address, int balance) 
    { 
     this.name = name; 
     this.phone = phone; 
     this.address = address; 
     this.balance = balance; 
     custData = name + phone + address + balance; 
    } 
1

你沒有設置任何比「custdata」等你的屬性,你需要設置屬性的其餘部分在構造函數了。

0

正如其他人說你不要在構造函數的值傳遞的任何指定的屬性。 要麼執行Romano建議的操作,要麼使用對象初始值設定項。

在構造函數中指定屬性。

​​

對象Initilizer一個默認的構造函數。

customers.Add(new Customer 
{ 
    Name = "Bill", 
    Phone = "555-555-5555", 
    Address = "2345 Some street", 
    Balance = "100000000" 
}); 

作爲一個側面說明,而不是使用公共領域「custData」試圖重寫ToString方法來返回所有的連結數據。