如何调用类中的方法
本文关键字:方法 调用 何调用 | 更新日期: 2023-09-27 18:01:51
自学c#(不是家庭作业)。我编写了一个TotalDue方法来计算所有到期客户余额的总和(来自数组)。将它放在Customer类中,这样它就可以访问数据。我不知道如何在main中调用这个方法。如何显示总数?
class Program
{
static void Main(string[] args)
{
Customer[] customers = new Customer[2];
string customer;
int id;
double due;
// GET DATA AND FILL ARRAY
for (int x = 0; x < customers.Length; ++x)
{
GetData(out customer, out id, out due);
customers[x] = new Customer(customer, id, due);
}
// SORT ARRAY - NEEDS ICOMPARABLE<Customer> - PART 1
Array.Sort(customers);
// PRINT ARRAY WITH TOSTRING() OVERRIDE
for (int x = 0; x < customers.Length; ++x)
{
Console.WriteLine(customers[x].ToString());
}
//DON'T KNOW HOW TO CALL THE TOTAL DUE METHOD...
Console.ReadLine();
}
class Customer : IComparable<Customer> // SORT ARRAY - PART 2
{
private string CustomerName { get; set; }
private int IdNumber { get; set; }
private double BalanceDue { get; set; }
// CONSTRUCTOR
public Customer(string customer, int id, double due)
{
CustomerName = customer;
IdNumber = id;
BalanceDue = due;
}
//SORT THE ARRAY - PART 3
public int CompareTo(Customer x)
{
return this.IdNumber.CompareTo(x.IdNumber);
}
// OVERRIDE TOSTRING TO INCLUDE ALL INFO + TOTAL
public override string ToString()
{
return ("'nCustomer: " + CustomerName + "'nID Number: " + IdNumber + "'nBalance Due: " + BalanceDue.ToString("C2"));
}
// TOTAL DUE FOR ALL CUSTOMERS
static void TotalDue(Customer [] customers)
{
double Total = 0;
for (int x = 0; x < customers.Length; ++x)
Total += customers[x].BalanceDue;
Console.WriteLine("Total Amount Due: {0}", Total.ToString("C2"));
}
}
// GET DATA METHOD
static void GetData(out string customer, out int id, out double due)
{
Console.Write("Please enter Customer Name: ");
customer = Console.ReadLine();
Console.Write("Please enter ID Number: ");
int.TryParse(Console.ReadLine(), out id);
Console.Write("Please enter Balance Due: $");
double.TryParse(Console.ReadLine(), out due);
}
}
将TotalDue
方法public设置为c#默认的访问修饰符为private,然后再尝试。
class Customer : IComparable<Customer> // SORT ARRAY - PART 2
{
public static void TotalDue(Customer [] customers)
{
double Total = 0;
for (int x = 0; x < customers.Length; ++x)
Total += customers[x].BalanceDue;
Console.WriteLine("Total Amount Due: {0}", Total.ToString("C2"));
}
}
static void Main(string[] args)
{
// ...........
//............
Customer.TotalDue(customers);
}
c#默认的访问修饰符是private
。由于您的TotalDue
方法没有指定任何其他内容,因此它是private
。您可以将其更改为public
,并从Main
调用它。
在静态方法中添加公共访问修饰符,并使用类名调用它,或者删除static关键字,使其成为实例并调用类方法
让你的Customer类方法(TotalDue)公开而不是静态…